2: Data Structures
2.1 Lists: Your First Data Collection
A list is one of the most versatile and commonly used data structures in Python. Think of a list as a drawer that can store a collection of objects in a specific order. Each object, or element, has a unique place identified by its index.
Main characteristics of lists:
- Ordered: Elements have a fixed and defined order.
- Mutable: You can add, remove, or change elements.
- Allow duplicates: They can contain the same value more than once.
Creating and accessing lists
Lists are defined using square brackets []
, with elements separated by commas. The first element has index 0
, the second 1
, and so on.
# Create a list of fruits
fruits = ["apple", "banana", "grape", "orange"]
# Access an element by its index
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: grape
# You can also use negative indices to access from the end
print(fruits[-1]) # Output: orange
Common list methods
Python offers several methods to work with lists.
-
append()
: Adds an element to the end of the list.fruits.append("kiwi") print(fruits) # Output: ['apple', 'banana', 'grape', 'orange', 'kiwi']
-
insert()
: Inserts an element at a specific position.fruits.insert(1, "mango") print(fruits) # Output: ['apple', 'mango', 'banana', 'grape', 'orange', 'kiwi']
-
remove()
: Removes the first occurrence of a value.fruits.remove("grape") print(fruits) # Output: ['apple', 'mango', 'banana', 'orange', 'kiwi']
-
pop()
: Removes and returns the element at a given index.removed_fruit = fruits.pop(0) print(removed_fruit) # Output: apple print(fruits) # Output: ['mango', 'banana', 'orange', 'kiwi']
2.2 Tuples: Immutable Collections
A tuple is similar to a list, but with one key difference: it is immutable! This means that once you create it, you cannot change, add, or remove its elements. Think of a tuple as a "frozen" list.
Main characteristics of tuples:
- Ordered: Like lists, they maintain a defined order.
- Immutable: They cannot be modified once created.
- Allow duplicates: They can contain repeated values.
Creating and using tuples
Tuples are defined using parentheses ()
. They are often used to group data that should not change, such as coordinates or record data.
# Create a tuple of coordinates
coordinates = (10.5, 20.3)
# Access elements (same as in lists)
print(coordinates[0]) # Output: 10.5
# Trying to modify it will result in an error
# coordinates[0] = 12.0 # This will cause a TypeError
2.3 Dictionaries: Key-Value Data
A dictionary is a data structure that stores information in key-value pairs. Unlike lists and tuples, where you access data by a numeric index, in a dictionary you access values through their keys, which can be strings or numbers.
Main characteristics of dictionaries:
- Unordered (in versions prior to Python 3.7): The insertion order is not guaranteed.
- Mutable: You can add, change, or delete key-value pairs.
- Keys must be unique: You cannot have two identical keys.
Creating and manipulating dictionaries
Dictionaries are defined using curly braces {}
. Each key-value pair is separated by a colon :
.
# Create a user dictionary
user = {
"name": "Carlos",
"age": 35,
"city": "Madrid"
}
# Access a value through its key
print(user["name"]) # Output: Carlos
# Add a new key-value pair
user["email"] = "carlos@example.com"
print(user) # Output: {'name': 'Carlos', 'age': 35, 'city': 'Madrid', 'email': 'carlos@example.com'}
# Modify an existing value
user["age"] = 36
print(user) # Output: {'name': 'Carlos', 'age': 36, 'city': 'Madrid', 'email': 'carlos@example.com'}
# Delete a key-value pair
del user["city"]
print(user) # Output: {'name': 'Carlos', 'age': 36, 'email': 'carlos@example.com'}
2.4 Sets: Collections without Duplicates
A set is an unordered collection of unique elements. Sets are useful when you need to store a collection of items and ensure there are no duplicates.
Main characteristics of sets:
- Unordered: Elements have no index.
- Unique: Duplicate elements are not allowed.
- Mutable: You can add or remove elements.
Creating and using sets
Sets are defined using curly braces {}
or the set()
function. If you try to add an element that already exists, nothing will happen.
# Create a set with some duplicates (they will be removed automatically)
numbers = {1, 2, 3, 2, 4, 1, 5}
print(numbers) # Output: {1, 2, 3, 4, 5}
# Add a new element
numbers.add(6)
print(numbers) # Output: {1, 2, 3, 4, 5, 6}
# Remove an element
numbers.remove(3)
print(numbers) # Output: {1, 2, 4, 5, 6}
This module has given you an overview of the main data structures in Python. Choosing the right structure is crucial for writing efficient and organized code. How about moving on to the next module to master control flow and programming logic?