Python Data Structures
🗂️ Data Structures in Python
Description: Explore the powerful built-in data structures Python offers, such as lists, tuples, sets, and dictionaries.
Lists
Creating a List
Lists can hold multiple items in a single variable.
print(my_list)
Indexing and Slicing
Access elements by index and retrieve a slice.
print(my_list[1:])
[20, 30]
List Methods
Use built-in methods to modify lists.
my_list.remove(20)
print(my_list)
Tuples
Creating and Accessing a Tuple
Tuples are immutable, meaning you can't change them after creation.
print(my_tuple[1])
Tuple Immutability
Trying to change a tuple raises an error.
Sets
Creating a Set
Sets store unique items and remove duplicates automatically.
print(my_set)
Set Operations
Use mathematical set operations like union and intersection.
b = {3, 4}
print(a.union(b))
print(a.intersection(b))
{3}
Dictionaries
Creating a Dictionary
Dictionaries store key-value pairs.
print(person)
Accessing and Modifying
Access or change values using keys.
person['age'] = 26
print(person)
{'name': 'Alice', 'age': 26}
Dictionary Methods
Useful methods like .keys() and .values().
print(person.values())
dict_values(['Alice', 26])
Looping Through Dictionary
Iterate through keys and values using a loop.
age 26
Nested Dictionary
A dictionary can contain other dictionaries.
print(students['student1']['name'])