List Comprehension in Python

List Comprehension in Python is very powerful code to write because it uses only a single line of code.You can create a new list by transfer from the exiting list.

    We have three step to do:

  • Create a simple list which have items
  • Declare a new list you want to transfer to.
  • Using For loop 
  • Using Append method.

For example:

I want to transfer all elements in list to another list:

myCar=['Toyota', 'Mitsubishi','Volvo']
myNewCar=[]
for x in myCar:
  myNewCar.append(x)
  myNewCar.sort(reverse=True)
print(myNewCar)
#output:['Volvo', 'Toyota', 'Mitsubishi']  

All elements in myCar copy to myNewCar by method append until the end of list.

For example:

We just want to create  a new list from the existing list by filter item begin with the first letter.

myCar=['Toyota', 'Mitsubishi','Volvo','MG']
myNewCar=[]
for x in myCar:
   if 'M' in x:
    myNewCar.append(x)
print(myNewCar)
#output:['Mitsubishi', 'MG']  

The new list (myNewCar)  only get the items which contains the first letter ‘M’.

For example:

This is another way to write List Comprehension code in Python. 

Syntax: myList=[exp for x in list (set,tuple,..etc) if condition is true….]

myCar=['Toyota', 'Mitsubishi','Volvo','MG']
myNewcar=[x for x in myCar if x=='MG']
print(myNewcar)
#output: ['MG'] 

if myCar has item that equal to x, then the myNewCar will get x. So it means this condition is true because x==’MG’.

freecode4learn.com

Leave a Reply