Data Structures in Python

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.

my_list = [10, 20, 30]
print(my_list)
[10, 20, 30]



Indexing and Slicing

Access elements by index and retrieve a slice.

print(my_list[0])
print(my_list[1:])
10
[20, 30]



List Methods

Use built-in methods to modify lists.

my_list.append(40)
my_list.remove(20)
print(my_list)
[10, 30, 40]



Tuples

Creating and Accessing a Tuple

Tuples are immutable, meaning you can't change them after creation.

my_tuple = (1, 2, 3)
print(my_tuple[1])
2



Tuple Immutability

Trying to change a tuple raises an error.

# my_tuple[0] = 5 → This will raise a TypeError



Sets

Creating a Set

Sets store unique items and remove duplicates automatically.

my_set = {1, 2, 2, 3}
print(my_set)
{1, 2, 3}



Set Operations

Use mathematical set operations like union and intersection.

a = {1, 2, 3}
b = {3, 4}
print(a.union(b))
print(a.intersection(b))
{1, 2, 3, 4}
{3}



Dictionaries


Creating a Dictionary

Dictionaries store key-value pairs.

person = {'name': 'Alice', 'age': 25}
print(person)
{'name': 'Alice', 'age': 25}



Accessing and Modifying

Access or change values using keys.

print(person['name'])
person['age'] = 26
print(person)
Alice
{'name': 'Alice', 'age': 26}



Dictionary Methods

Useful methods like .keys() and .values().

print(person.keys())
print(person.values())
dict_keys(['name', 'age'])
dict_values(['Alice', 26])



Looping Through Dictionary

Iterate through keys and values using a loop.

for key, value in person.items(): print(key, value)
name Alice
age 26



Nested Dictionary

A dictionary can contain other dictionaries.

students = { 'student1': {'name': 'Bob', 'age': 20}, 'student2': {'name': 'Carol', 'age': 22} }
print(students['student1']['name'])
Bob