Junior — Middle
Can you give an example of how to use collections in Python to store data?
sobes.tech AI
Answer from AI
In Python, built-in collections such as lists, tuples, sets, and dictionaries are often used to store data.
For example, to store a list of users with their ages, you can use a dictionary:
users = {
'alice': 30,
'bob': 25,
'carol': 27
}
# Add a new user
users['dave'] = 22
# Get a user's age
print(users['alice']) # 30
If you need to store an ordered set of elements, a list is suitable:
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
print(fruits) # ['apple', 'banana', 'cherry', 'date']
For unique elements, a set is used:
unique_ids = {1, 2, 3}
unique_ids.add(2) # will not be added, since 2 already exists
print(unique_ids) # {1, 2, 3}
Thus, the choice of collection depends on the task and data requirements.