List Comprehension (Python) Explained
Image source: https://www.freecodecamp.org/news/list-comprehension-in-python/

List Comprehension (Python) Explained

List Comprehension (Python) Explained

List is one of the simplest and most common data structure in Python. Today in this article, we're going to take list to the next level with "list comprehension".

Simplest form of list comprehension

Here, we'll use this simple example to illustrate what list comprehension is, and how list comprehension would make your code more 'elegant'.

Suppose we want to create a list to store the squares of a range of numbers. Logically, we want to create an empty list, loop a range of numbers, square each number, append the result in the list.

# Create an empty list
squares = []


# Loop numbers in a range
for i in range(1,11):
? ? # Square the numbers and append to list
? ? squares.append(i**2)
? ??
print(squares)        
No alt text provided for this image

This few lines of code could be written in a single list comprehension as shown below:

# List comprehension
squareComp = [i**2 for i in range(1,11)]
print(squareComp)?        
No alt text provided for this image

Here, squareComp is a list with a built-in for loop. This can be powerful because this means we can pass any iterable into a list comprehension, e.g. another list.

Suppose we want to perform multiplication in a vector.

# Vector v
v = [2,-3,1]


# Multiply v explicitly
m = 4*v
print(m)        
No alt text provided for this image

Similar to multiplying a string, 3*"Hello" would output "HelloHelloHello". Similarly, 4*v would multiply the vector as a whole. Since a list is iterable, we can loop each element in the vector and store the result in another list.

# Vector Multiplication
w = [4*x for x in v]
print(w)?        
No alt text provided for this image

List Comprehension Syntax

No alt text provided for this image

To define a list comprehension, you need an expression. An expression is what you want to store in the new list. In squareComp, I would like to store the square of each value i where i is each element a collection of numbers in range 1 to 10.

List Comprehension with IF clause

No alt text provided for this image

Note that using "for" and "if", ":" is not needed in the syntax. In the conventional approach, "if" is indented in the for loop and the append is indented in the if clause.

numbers = [i for i in range(1,21)]?
print("The range given is:",numbers)


# Conventional approach
even_num = []
for num in numbers:
? ? if num%2==0:
? ? ? ? even_num.append(num)
print("Even numbers in the range given are:",even_num)         

In list comprehension, we would simply add if <test> at the end of the list comprehension.

# List comprehension approach
even_numComp = [num for num in numbers if num%2==0]
print("List Comprehension:",even_numComp)?        

Multiple Variables

What if you have more than 1 variables in your list or other form of dictionary like dictionary? Short answer: define the variables like you would in a normal for loop.

# student[i] is a tuple
student = [("Ali",1998),("Siti",1995),("Lim",1999),("Muthu",2000),("Meng",2003)]?


born90s = [name for (name,year) in student if year<2000]
print(born90s)?        
No alt text provided for this image

For now, that's everything we would cover for list comprehension in this article. There are more problems and more complicated scenarios for a list comprehension, but let's leave them for another day. If you find this article helpful for your connection, please share it so that more people can benefit from this.

See you again in next week's article. Thank you for reading till the end :)



要查看或添加评论,请登录

社区洞察

其他会员也浏览了