Uploaded by abdisagaruma

Python Data Structures: Lists, Tuples, Dictionaries

advertisement
Python Data Structures: Lists, Tuples, and Dictionaries
Lists
A list in Python is a collection of items that is ordered and mutable. Lists allow duplicate
elements and can store items of different data types.
# Example of a list
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
# Adding an item to a list
fruits.append("orange")
# Removing an item
fruits.remove("banana")
# Iterating through a list
for fruit in fruits:
print(fruit)
Tuples
A tuple is similar to a list but is immutable. Once created, its values cannot be changed.
Tuples are useful for representing fixed collections of items.
# Example of a tuple
coordinates = (10, 20, 30)
print(coordinates[1]) # Output: 20
# Tuples are immutable
# coordinates[1] = 40 # This will raise an error
# Packing and unpacking tuples
x, y, z = coordinates
print(x, y, z) # Output: 10 20 30
Dictionaries
A dictionary in Python is a collection of key-value pairs. Each key must be unique, and
values can be of any data type. Dictionaries are unordered in Python versions < 3.7, but
ordered in Python 3.7 and later.
# Example of a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
print(person["name"]) # Output: John
# Adding a key-value pair
person["job"] = "Engineer"
# Removing a key-value pair
del person["age"]
# Iterating through keys and values
for key, value in person.items():
print(f"{key}: {value}")
Comparison of Lists, Tuples, and Dictionaries
1. **Lists**: Ordered, mutable, and allow duplicate elements.
2. **Tuples**: Ordered, immutable, and allow duplicate elements.
3. **Dictionaries**: Unordered (Python < 3.7), ordered (Python 3.7+), mutable, and consist
of unique keys with associated values.
Download