Learn about List, Tuples, Sets, Dictionaries in Python
1. Lists
A list is a collection of items that are ordered and changeable. Lists allow duplicate members.
my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]
my_list.append(6) # Adding an element
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
Properties of Lists:
- Ordered: Items have a defined order.
- Mutable: Items can be changed.
- Allows duplicates: Multiple items can have the same value.
2. Tuples
A tuple is similar to a list, but it is immutable. Once a tuple is created, you cannot change its values.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple) # Output: (1, 2, 3, 4, 5)
# my_tuple[0] = 10 # This will raise a TypeError
Properties of Tuples:
- Ordered: Items have a defined order.
- Immutable: Items cannot be changed.
- Allows duplicates: Multiple items can have the same value.
3. Dictionaries
A dictionary is a collection of key-value pairs. Dictionaries are unordered, changeable, and do not allow duplicate keys.
my_dict = {"name": "Alice", "age": 25}
print(my_dict) # Output: {'name': 'Alice', 'age': 25}
my_dict["age"] = 30 # Changing a value
print(my_dict) # Output: {'name': 'Alice', 'age': 30}
Properties of Dictionaries:
- Unordered: Items do not have a defined order.
- Mutable: Items can be changed.
- No duplicate keys: Each key must be unique.
4. Sets
A set is an unordered collection of unique items. Sets are mutable, but they cannot contain duplicate elements.
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
my_set.add(6) # Adding an element
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
my_set.add(3) # Adding a duplicate will not change the set
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
Properties of Sets:
- Unordered: Items do not have a defined order.
- Mutable: Items can be changed.
- No duplicate elements: Each item must be unique.
Comparison of Lists, Tuples, Dictionaries, and Sets
Property | List | Tuple | Dictionary | Set |
---|---|---|---|---|
Ordered | Yes | Yes | No | No |
Mutable | Yes | No | Yes | Yes |
Duplicates | Yes | Yes | No (keys) | No |
Access | By index | By index | By key | By value |
Comments
Post a Comment