List Comprehension

  • List Comprehension is the method of creating new list from an existing list using a short syntax
  • With list comprehension you can do all that with only one line of code.
Syntax

[variable1 for variable2 in iterable condition]

Where variable1= Return value

Variable2= input value

For, in= loop elements

iterable condition = iterator that is run for each input value and the return value is derived

[]= braces depicting that this is List comprehension statement
[x for x in range(10) if i % 2 ==0]

[0, 2, 4, 6, 8]  #conditional statment

Color = ["red", "blue", "green", "gray", "black"]

output = [x for x in colurs if "a" in x]

The condition is optional and can be omitted

Mylist = [1,2,3,45,5]

newlist = [x for x in  Mylist ] #no if statment

you can manipulate before it ends up like a list item in the new list:

Mylist = [‘hello’,’hi’]

newlist = [x.upper() for x in Mylist]

Nested Loops

list2 = [y for x in [2, 4] for y in [x, x*3]]

print(list2)

Nested List comprehension

  • Nested lists i.e. list of lists can also be handled well by List comprehension.
  • For loop can be put for each nested list within the main list.
months = [['January', 'February', 'March'], ['April', 'May', 'June'], ['July', 'August', 'September'],['October','November','December']]

months = [months for sublist in months for months in sublist if len(months) <= 4]
print(months)

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *