top of page
Writer's pictureLearner Landmark

9 things to know to Master List Comprehension in Python

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.


A pair of square brackets containing the expression, which is executed for each element in the iterable.


1. Syntax
# list comprehension
[expression for item in iterable]

# expanded form
for item in iterable:
   expression

The expanded form is usually expressed as a for loop, in which each item of the iterable runs certain operation as specified in the expression.


2. Create a List

Suppose if we don't know the list comprehension feature, then probably we need to write the following code to create a list.



fruits = ['apples', 'oranges', 'grapes']

uppercase_fruits =[]
for item in fruits:
    uppercase_fruits.append(item.upper())

print(uppercase_fruits)

#output
['APPLES', 'ORANGES', 'GRAPES']

We can "compress" the for-loop statement in one line - using the comprehension syntax:


fruits = ['apples', 'oranges', 'grapes']

uppercase_fruits = [item.upper() for item in fruits]
print(uppercase_fruits)

# output
['APPLES', 'ORANGES', 'GRAPES']

3. Conditional Statement for Filtering

Sometimes, we don't need all items in the given list, then we can filter some items based on some condition.



#list comprehension with a conditional statement
[expression for item in iterable if some_condition]

#expanded form
for item in iterable:
    if some_condition:
        expression

for example:

numbers = [1,2,3,4,5,6,7,8,9,10]

even_numbers= [number for number in numbers if number%2 == 0]
print(even_numbers)

# output
[2, 4, 6, 8, 10]

If we have a more complicated evaluation of the condition, we can go with the callback function.

4. Conditional Assignment

Sometimes, we don't want to filter out the items from the original list. Instead, we want to evaluate the condition to determine which expression is used.


for example, you want to apply salary rise based on their current salary.


5. Instead of map ()

map () is used to apply a transformation to every element in an iterable. and returns an iterable object, which is to be converted into list using list() function.


salaries = [10000,20000,60000, 70000]
print(list(map(lambda sal: sal*1.10, salaries)))
# [11000.0, 22000.0, 66000.0, 77000.0]

hike_salaries = [sal * 1.10 for sal in salaries]
print(hike_salaries)
# [11000.0, 22000.0, 66000.0, 77000.0]

6. Nested List Comprehensions

Suppose that we have a list of tuples in following code snippet, and we want to make it as a list.


list1 = [(1,2,3), (4,5,6), (7,8,9)]
list2 = [item for tup in list1 for item in tup]

print(list2)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

7. Walrus Operator in List Comprehensions

The walrus operator, introduced in Python 3.8, offers a way to accomplish two tasks at once: assigning a value to a variable, and returning that value, which can sometimes offer a way to write shorter, more readable code, that may even be more computationally efficient.


>>> num = 10
>>> print(num)
10

Instead of writing two lines of code, we can write it in one line.


>>> print(x := 100)
100

Walrus operator allows us to both assign a value to a variable, and to return that value, all in the same expression.


following code snippet shows, how to use walrus operator in list comprehension:

8. Set Comprehension

The set comprehension defined with a pair of curly braces. The elements in the set won't allow the duplicates.

list1 = [1,2,3,2,3,1,2,1,3,4,5,4,6]

# filters unique even numbers from a list
set1 = {x for x in list1 if x%2 == 0}
print(set1)

# output
{2, 4, 6}

9. Dictionary Comprehension

We have list and set comprehensions; dictionary comprehension syntax is:


Syntax:

{key_expression : value_expression for item in iterable}

How many times each word repeated in the given string?

input: "abc abd aaa abc abd abb"

 
Thanks for reading!!!

Your Rating and Review will be appreciated!!

Twitter: @LearnerLandmark



Recent Posts

See All

Comentarios

Obtuvo 0 de 5 estrellas.
Aún no hay calificaciones

Agrega una calificación
bottom of page