Python provides a variety of built-in data structures, such as lists, tuples, sets, and dictionaries. Each serves unique purposes and can help make code more efficient and organized.
Data Structures in Python
1. Lists
A list is an ordered, mutable data structure in Python that allows duplicate elements. Lists are created using square brackets:
my_list = [1, 2, 3, 4, 5]
print(my_list)
Lists support various methods like append()
, remove()
, and sort()
:
my_list.append(6) # Adds 6 to the end
my_list.remove(3) # Removes the element with value 3
my_list.sort() # Sorts the list in ascending order
Lists Quiz
How do you add an element to the end of a list?
What makes lists different from tuples?
2. Tuples
A tuple is similar to a list but is immutable, meaning once created, its elements cannot be changed. Tuples are defined using parentheses:
my_tuple = (10, 20, 30)
print(my_tuple)
Because tuples are immutable, they are often used for fixed collections of items.
Tuples Quiz
What happens if you try to modify a tuple element?
When would you use a tuple instead of a list?
3. Sets
A set is an unordered collection of unique elements. Sets are useful for storing distinct items and for membership testing:
my_set = {1, 2, 3, 4, 5}
my_set.add(6) # Adds 6 to the set
my_set.remove(3) # Removes the element with value 3
Sets do not allow duplicate elements and are defined using curly braces.
Sets Quiz
What happens if you try to add a duplicate element to a set?
What's the main advantage of using sets?
4. Dictionaries
A dictionary is a collection of key-value pairs. Dictionaries are unordered, mutable, and defined with curly braces:
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict['name']) # Outputs: Alice
Dictionaries are great for representing structured data, where each key points to a specific value. Methods include get()
, keys()
, and values()
.
Dictionaries Quiz
How do you safely access a dictionary value that might not exist?
What happens if you try to use a list as a dictionary key?