Python list comprehension

python list comprehension

What is list comprehension in python?

List comprehension gives you a more concise and straightforward way of creating new lists using loops compared to the traditional approach of creating new list. Which makes our code easier to read and understand. List comprehension is a trait of intermediate-level developers. We often see list comprehension questions in interviews which makes it an important concept in programming.

We will learn how to use if else in list comprehension and nested list comprehension with different applicable scenarios.

Syntax :

new_list = [expression for item in iterable if condition]

Understanding the above code

  • “expression” is the value to be included in the new list we are creating.
  • “Item” is  the variable representing each element in the iterable. Iterable can be a list, tuple, set or dictionary.
  • “Iterable” is the sequence of elements to iterate over.
  • “condition”  is optional if you want to just loop over the element in an iterable. We only use “condition” to filter values to be added in the new list. 

Now, let’s jump to code.

Example 1 : Loop over a list using list comprehension.  

If you want to loop over a list of paragraphs and want to convert a paragraph to a list of words. You can follow the below code

 

paragraphs = [“This is the first paragraph.”, “And here is the second paragraph.”,
“The last one is the third paragraph.”]

word_lists = [paragraph.split() for paragraph in paragraphs]

print(word_lists)

#output : [[‘This’, ‘is’, ‘the’, ‘first’, ‘paragraph.’], [‘And’, ‘here’, ‘is’, ‘the’, ‘second’, ‘paragraph.’], [‘The’, ‘last’, ‘one’, ‘is’, ‘the’, ‘third’, ‘paragraph.’]]

 

Example 2: If statement in list comprehension

Getting  all the even numbers in a list using the if condition in list comprehension. 

numbers=[12,3,67,34,56]

even_numbers = [x for x in numbers if x % 2 == 0]  

print(even_numbers)

 

#output :[12, 34, 56]

We will Filter a list by keeping words only containing “a” in them.

 

word_list=[‘apple’,‘ball’,‘cat’,‘dog’,‘elephant’]

words_with_a = [word for word in word_list if “a” in word]  

print(words_with_a)

 

#output: [‘apple’, ‘ball’, ‘cat’, ‘elephant’] 

Example 3 : If else statement in list comprehension 

Classifying number either positive or negative using if else statement in list comprehension

numbers=[12,3,67,34,56]

positive_negative = [(“positive”,x) if x > 0 else (“negative”,x) for x in numbers]

print(positive_negative )

 

#output:[(‘positive’, 12), (‘positive’, 3), (‘negative’, 67), (‘positive’, 34), (‘negative’, 56)]

Example 4: Nested list comprehensions

Getting all the combinations of elements in the given two lists using nested list comprehension.

char=[‘a’,‘b’,‘c’]

number=[1,2,3]

all_pairs = [(x, y) for x in char for y in number]

print(all_pairs)

 

#output:[(‘a’, 1), (‘a’, 2), (‘a’, 3), (‘b’, 1), (‘b’, 2), (‘b’, 3), (‘c’, 1), (‘c’, 2), (‘c’, 3)]

Example  5 : List comprehension with dictionary comprehension

Squares of numbers as a dictionary

square_dict = {key: key**2 for key in range(5)}

#output {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

 

Creating a new dictionary by keeping item whose values are greater than 10

data={1:1,2:4,3:9,4:12,5:25}

filtered_dict = {key: value for key, value in data.items() if value > 10}

print(filtered_dict)

#Output: {4: 12, 5: 25}

 

Example 6: List comprehension with set

Create a set of unique even numbers from a list

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

unique_even_set = {x for x in numbers if x % 2 == 0}

print(unique_even_set)

#Output :{2, 4, 6}

Example 7 : List comprehension with Zip and enumerate function

Create a list of sums of corresponding elements from two lists using zip function in list comprehension.
 

list1 = [1, 2, 3]

list2 = [4, 5, 6]

sums = [x + y for x, y in zip(list1, list2)]

print(sums)

#output : [5, 7, 9]

 

Create a list of squares with their indices using enumerate function in list comprehension.

numbers = [2, 4, 6, 8, 10]

squares_with_indices = [(index, num**2) for index, num in enumerate(numbers)]

print(squares_with_indices)

#output [(0, 4), (1, 16), (2, 36), (3, 64), (4, 100)]

  

Example 8 : Transforming elements using list comprehension

Create a list of upper case character from word using list comprehension.

uppercase_letters = [char.upper() for char in “hello”]  

print(uppercase_letters)

#output :[‘H’, ‘E’, ‘L’, ‘L’, ‘O’]

 

 

Pros 

  • Single line of code increases conciseness and readability of code. 
  • Faster as compared to traditional for loop in some cases due to internal optimizations.
  • Lesser code leads to fewer opportunities for typos or errors.
  • Reduce overall lines of code in the program.

Cons

  • Using a nested list increases complexity of the code and decreases readability.
  • Debugging code within a single line is more challenging.

A good developer always maintains balance between complexity and readability of code. 

You can get the code on github.