Lists in Python: creation - access - and useful methods
Lists are the most flexible and widely used data structures in Python. They can contain any type of elements, can be modified, and allow fast access to information.
Creating lists
fruits = ["apple", "pear", "banana"]
numbers = [1, 2, 3, 4]
mix = [True, 3.14, "text"]
Accessing elements
print(fruits[0]) # Displays: apple
print(fruits[-1]) # Displays: banana
print(fruits[1:3]) # Displays: ['pear', 'banana']
Useful list methods
fruits.append("cherry") # Adds an element at the end
fruits.insert(1, "plum") # Inserts at index 1
fruits.remove("pear") # Removes the first element with the given value
fruits.pop() # Removes the last element
fruits.sort() # Sorts the list
fruits.reverse() # Reverses the order
print(len(fruits)) # Displays the length of the list
- Lists can contain duplicate elements and different types.
- Indexing starts at 0.
- The
append()andpop()methods are frequently used in algorithms.
Tuples and sets in Python
Tuples and sets are special data structures in Python. Tuples are immutable, while sets do not allow duplicates. Both are useful in different contexts.
Tuples
# Creation
coord = (10, 20)
# Access
print(coord[0]) # Displays: 10
# Tuple with a single element
solo = (42,) # The comma is mandatory
Sets
# Creation
colors = {"red", "green", "blue", "red"}
# Remove duplicates
print(colors) # Displays: {'red', 'green', 'blue'}
# Add and remove
colors.add("yellow")
colors.remove("green")
- Tuples are useful when you want a fixed collection of data.
- Sets are ideal for quick membership checks.
- Sets do not guarantee the order of elements.
Dictionaries in Python: keys and values
Dictionaries are data structures that store key-value pairs. They are ideal for fast access to information and clear organization.
Creating dictionaries
student = {
"name": "John",
"age": 17,
"class": "XI-A"
}
Accessing values
print(student["name"]) # Displays: John
print(student.get("age")) # Displays: 17
Modifying and adding
student["age"] = 18
student["profile"] = "Math-CS"
Deletion
del student["class"]
student.pop("profile")
Iterating through a dictionary
for key in student:
print(key, student[key])
for key, value in student.items():
print(f"{key}: {value}")
- Keys must be unique and of immutable types (e.g., string, number, tuple).
- The
get()method is safer than direct access, avoiding errors if the key does not exist. - Dictionaries are extremely efficient for fast lookups.
Iterating through data structures
Iteration is the process of going through the elements of a data structure. Python offers a simple and intuitive syntax to work with lists, tuples, sets, and dictionaries.
Iterating through a list
fruits = ["apple", "pear", "banana"]
for fruit in fruits:
print(fruit)
Iterating through a tuple
coord = (10, 20)
for value in coord:
print(value)
Iterating through a set
colors = {"red", "green", "blue"}
for color in colors:
print(color)
Iterating through a dictionary
student = {"name": "John", "age": 17}
for key in student:
print(key, student[key])
for key, value in student.items():
print(f"{key}: {value}")
- You can use
enumerate()to also get the index during iteration. - The
items()function is ideal for accessing both keys and values of a dictionary simultaneously. - The order of elements in sets is not guaranteed.
List Comprehension in Python
List comprehension is a concise and elegant method to create lists based on expressions and conditions. It is faster and more readable than using classic loops.
Creating a list of squares
# Classic version
squares = []
for x in range(5):
squares.append(x * x)
# List comprehension
squares = [x * x for x in range(5)]
print(squares) # Displays: [0, 1, 4, 9, 16]
List comprehension with condition
# Even numbers from a range
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Displays: [0, 2, 4, 6, 8]
Text transformations
words = ["python", "is", "cool"]
uppercase = [c.upper() for c in words]
print(uppercase) # Displays: ['PYTHON', 'IS', 'COOL']
- List comprehension is ideal for quickly generating transformed lists.
- You can include conditions for filtering directly in the expression.
- It can also be used with functions or complex expressions.
Dict Comprehension and Set Comprehension in Python
Comprehensions for dictionaries and sets provide a fast and expressive way to build data structures based on rules or transformations. They are ideal for filtering, mapping, and dynamic generation.
Dict comprehension
# Create dictionary with squares
squares = {x: x * x for x in range(5)}
print(squares) # Displays: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Filtering
numbers = [1, 2, 3, 4, 5]
even = {x: x for x in numbers if x % 2 == 0}
print(even) # Displays: {2: 2, 4: 4}
Set comprehension
# Create set with squares
squares = {x * x for x in range(5)}
print(squares) # Displays: {0, 1, 4, 9, 16}
# Filtering
letters = "programming"
vowels = {c for c in letters if c in "aeiou"}
print(vowels) # Displays: {'a', 'e', 'o'}
- Comprehensions are faster than classic loops for generating structures.
- Dict comprehension uses the syntax
{key: value for ...}. - Set comprehension automatically removes duplicates.
