List Comprehension in python 3: Complete guide(With example code)

Data Science May 31, 2019

List comprehensions provide a concise way to create lists in python.

Common applications of List Comprehension are to make new lists where each element is the result of some operations or functions applied to each member of another sequence,

The list comprehension always returns a resulting list.

All kinds of object can be put into the list.

Basic syntax: How to write list comprehension in python

new_list = [expression for_loop_one_or_more condtions]

*result*  = [*transform*    *iteration*    *filter*]

Now let's see how list Comprehension can make our life easier, and how does list comprehension work in python.

Example:1

How to use list comprehension in python to creating a list?

list1 = [x for x in range(10)]
list1


#output is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Example:2

Applying Square function on all the numbers

Idea can be extended for Adding , Subtracting,applying certain function on all the numbers in the list.

# Without List Comprehension

numbers = [4,5,6,10]
squares = []

for n in numbers:
  squares.append(n**2)

print(squares)  # Output: [16, 25, 36, 100]



# With  List Comprehension


numbers =  [4,5,6,10]
squares = [n**2 for n in numbers]

print(squares)  # Output: [16, 25, 36, 100]

Example:3

Some common use case using list comprehension in python with for loop.

a) Converting Upper an Lower Case

list_a = ["Data", "Discuss", "Is", "Awesome"]

small_list_a = [str.lower() for str in list_a]

print(small_list_a) 


# Output: ['data', 'discuss', 'is', 'awesome']

list_a = ["Data", "Discuss", "Is", "Awesome"]

large_list_a = [str.upper() for str in list_a]

print(large_list_a) 


# Output: ['DATA', 'DISCUSS', 'IS', 'AWESOME']

b)  Extracting Digits and characters from string

string = "Hello 12345 Data Discuss"
numbers = [x for x in string if x.isdigit()]
print(numbers)

# Output: ['1', '2', '3', '4', '5']


string = "Data 101101 Discuss"
characters = [x for x in string if x.isalpha()]
print(characters)

# Oputput:  ['D', 'a', 't', 'a', 'D', 'i', 's', 'c', 'u', 's', 's']

C)  Producing list of list

list_a = [1, 2, 3]

square_cube_add_list = [ [a**2, a**3 ,a+10] for a in list_a]

print(square_cube_add_list) 

# Output: [[1, 1, 11], [4, 8, 12], [9, 27, 13]]

Example :4

List comprehension if else
Using Conditional  if Statements within List Comprehension.

a) Finding common numbers from two list

# Without List Comprehension

list_a = [1, 6, 9, 2, 3, 4]
list_b = [2, 3, 4, 5,6]

common_num = []

for a in list_a:
  for b in list_b:
    if a == b:
      common_num.append(a)
      
print(common_num)  # Output [6, 2, 3, 4]


#Boring \!!! ugh


# With List Comprehension

list_a = [1, 6, 9, 2, 3, 4]
list_b = [2, 3, 4, 5,6]

common_num = [a for a in list_a for b in list_b if a == b]

print(common_num) # Output: [6, 2, 3, 4]

b)  Some mathematics

number_list1 = [ x for x in range(20) if x % 2 == 0]
print(number_list1)

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


## Nested IF with List Comprehension

num_list2 = [y for y in range(100) if y % 2 == 0 if y % 5 == 0]
print(num_list2)

# Output : [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

Example :5

if else With List Comprehension

list2 = ["Even" if i%2==0 else "Odd" for i in range(10)]
print(list2)

# Output : ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']

Example :6

Using Multiple lists with List Comprehension

list3 = [x+y for x in [10,30,50] for y in [20,40,60]]
print(list3)


# Output : [30, 50, 70, 50, 70, 90, 70, 90, 110]

Example :7

Taking Input with list comprehension

list4 = [int(x) for x in input().split()]

# Input prompt will be open

So why we are using list comprehension over for loop: Give answer in comment box below

Thanks For reading .

Our other intresting post about Data Science and Machine learning:

P.S:

Tell us about the topics that you want to explore we'll try to give the best possible material realted to that topic

sheetala tiwari

I am passionate about Data Science and Machine Learning. I am currently building an AI community on DataDiscuss and we are committed to providing free access to education for everyone.