Lists#
Lists are one of the most valuable and frequently used data types in Python, found at the heart of countless Python programs. So, what exactly is a list, and why are they so indispensable?
In essence, a list is a dynamic and mutable collection of values. Think of it as a versatile bag that can store a variety of items—numbers, words, and even a medley of data types—all within a single container. This flexibility makes lists an invaluable asset for any Python programmer.
Let’s explore the concept further with a real-world analogy. Imagine you have a collection of names, distances, and mixed data types like this:
users = ["Jim", "Dwight", "Michael"]
distance_in_kms = [32, 97, 51, 403, 21, 53, 81]
mixed_types = ["Jim", 23, 3.14, True, "Berzerk"]
In this example, users
contains a list of names as strings, distance_in_kms
stores a list of distances in ints
, and mixed_types
is a list that seemingly defies convention by accommodating a diverse set of data types. Lists are incredibly powerful because they allow you to organize and manipulate such data effortlessly.
Accessing List Items#
List items can be accessed via their index system, like this:
users = ["Jim", "Dwight", "Michael"]
print(f"What is your favourite moment when {users[0]} pulls a prank on {users[1]}?")
What is your favourite moment when Jim pulls a prank on Dwight?
Or can even be accessed through negative indexing, like this:
users = ["Jim", "Dwight", "Michael"]
print(f"What was one thing that {users[-1]} did you found extra funny?")
What was one thing that Michael did you found extra funny?
For more information about accessing list items, see Slicing.
Adding and Removing Items from Lists#
What makes lists truly exceptional is their mutability. Unlike some data types in Python, lists can change and adapt as your program runs. You can add, remove, or modify elements within a list, making it a dynamic tool for handling evolving data. This adaptability is particularly useful in scenarios where you need to manage collections of data that may grow or shrink in size.
users = ["Jim", "Dwight", "Michael"]
users.append("Pam")
print(f"We've added {users[-1]} to the list!")
We've added Pam to the list!
List Comprehensions#
A slightly more advanced topic, Python list comprehensions are a concise and efficient way to create lists in Python. They allow you to generate a new list by applying an expression to each item in an existing iterable (e.g., a list, tuple, or range) and optionally applying a filter condition to include only certain items. List comprehensions are a more compact alternative to using traditional for loops to build lists.
The basic syntax of a list comprehension is as follows:
#new_list = [expression for item in iterable if condition]
Here’s a breakdown of each part:
expression
: This is the expression that you want to apply to each item in the iterable to generate the elements of the new list.item
: A variable that represents each item in the iterable.iterable
: The existing iterable from which you are generating the new list.condition
(optional): An optional condition that filters the items from the iterable. If specified, only items that satisfy this condition will be included in the new list.
Now, let’s look at some examples to illustrate list comprehensions. First, let’s generate the numbers 0-9 with a list comprehension:
squares = [x ** 2 for x in range(10)]
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Next, use a list comprehension to filter out even numbers from the numbers list based on the condition x % 2 == 0
:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
[2, 4, 6, 8, 10]
Or, create a list of uppercase characters from the text string while ignoring non-alphabetic characters:
text = "I am 12 years old!"
uppercase_chars = [char.upper() for char in text if char.isalpha()]
print(uppercase_chars)
['I', 'A', 'M', 'Y', 'E', 'A', 'R', 'S', 'O', 'L', 'D']
List comprehensions can be a powerful tool to simplify code when you need to transform or filter data in lists or other iterables. They make your code more concise and easier to read while still being efficient.
If you’d like further information about list comprehensions, check out this video from Socratica: