Home > Back-end >  what type of loops are [i for i in x for i! =0] in python?
what type of loops are [i for i in x for i! =0] in python?

Time:05-12

say I have a list:

c = ['A','B','C','']

I loop over it to print without the empty element '' using this code:

for i in c: 
    if i != '': 
        print(i)
        i = i
    else: 
        pass



outputs: 
A
B
C

I can also do this using:

[i for i in x for i!=0]


outputs: 

['A',
 'B',
 'C']

My question is what is this below type of loop called? How to add an if else statement to this loop? and any material that will help me know more about it.

CodePudding user response:

It's called list comprehension.

You can get the desired list(d) with if condition as follows

c = ['A','B','C','']

d = [i for i in c if i!= '']

CodePudding user response:

It's called list comprehension.

There are two ways of doing if statements:

>>> a = [5, 10, 15, 20, 25, 30, 35]
>>> b = [i for i in a if i % 3 == 0]
>>> b
... [15, 30]


>>> c = [i if i % 3 == 0 else 0 for i in a]
>>> c
... [0, 0, 15, 0, 0, 30, 0]

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.

Find out more on list comprehension in the python docs at this link:

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

  • Related