Python List Comprehension

Python List Comprehension is the process of creating a new list from items of another existing list. The List comprehension is used to read existing list items and process them and then create a new list from the processed items accordingly.

List Comprehension Syntax

The list comprehension has the following syntax which is very PYthonic.

  • NEWLIST is the returned list after the list comprehension is complete.
  • EXPRESSION is the executed statement or expression in each iteration of the list comprehension.
  • ITEM is the item of the ITERABLE in each iteration.
  • ITERABLE is an iterable variable like list, dictionary, set, etc. which is iterated.
  • CONDITION is a check if the specified condition is met for the current iteartion.

List Comprehension with String List

We start with a simple example where a list of strings is comprehensive. The list is named as names and names containing with a is returned for the new list as items. Other names are discarded and not added to the new list named new_names .

names = [ "ismail" , "ali" , "ahmet" , "elif" ]

new_names = [ name for name in names if "a" in name]


List Comprehension with Integer List

The list comprehension can be do with an integer list where all items of the list is integer type. In the following example we select integers which are higher than 10.

values = [ 12,2,4,5,13,4,5,23 ]

new_values = [ i for i in values if i > 10 ]


Simple List Comprehension

The List comprehension CONDITION part is optional which means we can omit the CONDITION and use only the EXPRESSION. This makes the list comprehension simpler. In the following example, we iterate over all list items and multiply them by 2 using the EXPRESSION.

values = [ 12,2,4,5,13,4,5,23 ]

new_values = [ i*2 for i in values ]


List Comprehension using range() Method

The range() function is used to create sequences which can be iterable and mostly used for loops and iterations. The range() method can be used with the list comprehension in order to iterate integer list which is a sequence. In the following example we iterate over the list from 1 to 10 using list comprehension.

new_values = [ i*2 for i in range(10) ]

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Leave a Comment