Differences Between Dictionaries, Tuples and List
Differences Between Dictionaries, Tuples and List
1. Lists:
o Definition: Ordered collection of items.
o Syntax: Defined using square brackets: [].
o Properties:
Mutable: You can modify, add, or remove items after the list is created.
Indexing: Elements can be accessed by their index.
o Use Cases: Useful when you need an ordered, modifiable sequence of items.
o Example:
python
Copy code
my_list = [1, 2, 3, 4]
2. Tuples:
o Definition: Ordered collection of items, similar to lists, but immutable.
o Syntax: Defined using parentheses: ().
o Properties:
Immutable: Once created, the elements cannot be changed (no addition, deletion, or
modification).
Indexing: Elements can be accessed by their index, just like lists.
o Use Cases: Useful for storing fixed data that should not be changed.
o Example:
python
Copy code
my_tuple = (1, 2, 3, 4)
3. Dictionaries:
o Definition: Unordered collection of key-value pairs.
o Syntax: Defined using curly braces: {}.
o Properties:
Mutable: You can add, remove, or change key-value pairs after the dictionary is created.
Key-Value Pairs: Each element has a key and a corresponding value.
No Indexing: Elements are accessed by their key, not by index.
o Use Cases: Useful when you want to store data as key-value pairs, like a mapping or a record.
o Example:
python
Copy code
my_dict = {'name': 'John', 'age': 30}
Meaning of Immutable
python
Copy code
my_tuple = (1, 2, 3)
# This will raise an error:
my_tuple[0] = 10
In contrast, a list is mutable because you can modify its contents after creation:
python
Copy code
my_list = [1, 2, 3]
my_list[0] = 10 # No error
python
Copy code
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3, 4)