The square brackets []
in Python are used to denote a list, while the curly braces {}
are used to denote a dictionary.
These symbols play a significant role in Python’s data structures, and understanding their differences is essential for efficient programming.
In Python, a list is a versatile data structure that can store a collection of elements. These elements can be of any data type, allowing for the creation of heterogeneous lists.
Lists maintain the order of elements, and Python follows zero-based indexing, where the first element has an index of 0, the second element has an index of 1, and so on.
Lists offer flexibility and efficiency, making them suitable for various applications.
They are commonly used to manage lists of items, track user inputs, and store data sets that require sequential processing.
To create a list in Python, you simply enclose the elements within square brackets []
and separate them with commas.
Here’s an example code:
my_list = [1, 'hello', 3.14, True]
Elements in a list can be accessed using their index values. For example, to access the second element in the above list, you would use:
print(my_list[1])
hello
Lists are mutable, which means you can modify their elements after creation. You can add elements, remove elements, or modify existing ones as needed during the course of your program.
Read more on: What is a List in Python with Example?
In Python, a dictionary is another essential data structure that stores a collection of key-value pairs.
Unlike lists, dictionaries do not rely on numerical indexing. Instead, they use keys to access corresponding values.
Dictionaries are valuable when dealing with data that requires quick lookups and searching based on specific identifiers.
They provide a direct mapping between keys and their associated values.
To create a dictionary in Python, you enclose the key-value pairs within curly braces {}
and separate them using colons :
.
Each key-value pair is separated by a comma.
Here’s also an example code:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
To access values in a dictionary, you use the corresponding key. For example:
print(my_dict['name'])
John
Like lists, dictionaries are mutable. You can modify existing key-value pairs, add new ones, or remove entries as needed during program execution.
Read more on: Python Dictionaries: A Beginner’s Guide with Example
As a wrap up, the difference between using square brackets []
and curly braces {}
in Python is that, square brackets []
are used for creating lists while curly braces {}
are used to create dictionaries.
Lists are ordered collections that use numerical indexing, while dictionaries are associative collections that rely on keys for direct access to values.
append()
method to add an element at the end or the insert()
method to insert an element at a specific index.