Introduction to list comprehension
This tutorial explores list comprehension in Python—a concise way to create lists from iterables. We’ll cover the basic syntax, usage, and show how list comprehension can often replace traditional for-loops.
Let's talk about list comprehension in Python.
List comprehension is a concise way to create lists in Python.
It allows you to generate a new list by applying an expression to each item in an existing iterable.
The basic syntax of list comprehension is:
new_list = [expression for item in iterable]
It's basically a for loop inside a list statement.
For instance, let's say you want to create a list of squares for numbers from 0 to 9.
In a traditional for-loop we would do it like this:
squares = []
for x in range(10):
squares.append(x**2)
print(squares)
Using list comprehension, we can achieve the same result in a single line of code:
squares = [x**2 for x in range(10)]
print(squares)
Here, we loop through a range from 0-9. Each integer is temporarily assigned to the variable x
.
Next, we calculate x**2
and immediately save the result as a new item in the squares
list.
Now, let's look at another example.
Let's say we have a list of words and we want to create a new list that contains the length of each word.
words = ['apple', 'banana', 'cherry', 'date']
lengths = [len(word) for word in words]
print(lengths)
First, we loop through words
and temporarily assign each word to the variable word
.
Then, we use len
to count the number of characters and assign the result as a new item in the lengths
list.
What will be the output?
numbers = [1, 2, 3, 4, 5]
squared_numbers = [n**2 for n in numbers]
print(squared_numbers)
What will be the output?
sentence = 'Add a comment'
word_lengths = [len(word) for word in sentence.split()]
print(word_lengths)
What will be the output?
uppercase_chars = [char + char for char in 'abcd']
print(uppercase_chars)