Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'while' loops in a list comprehension

Say I have a function:

x=[]
i=5
while i<=20:
     x.append(i)
     i=i+10
return x

Is there a way to convert it to a list comprehension like this?

newList = [i=05 while i<=20 i=i+10]

I get a syntax error.

like image 979
cashmoney11 Avatar asked Mar 09 '17 23:03

cashmoney11


People also ask

Are list comprehensions better than for loops?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.

Can we use while loop in dictionary?

Sure you can use a while loop, every for loop can be written as a while loop if you really have to for some reson but I don't see any advantages over your for loop.

Why list comprehension is faster than for loop?

List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.

Are list comprehensions good practice?

List comprehensions are great because they require less lines of code, are easier to comprehend, and are generally faster than a for loop.


2 Answers

You don't need a list comprehension for that. range will just do:

list(range(5, 21, 10)) # [5, 15]

A while loop is not possible inside of a list comprehension. Instead, you could do something like this:

def your_while_generator():
    i = 5
    while i <= 20:
        yield i
        i += 10

[i for i in your_while_generator()]
like image 124
Francisco Avatar answered Sep 19 '22 16:09

Francisco


No, you cannot use while in a list comprehension.

From the grammar specification of Python, only the following atomic expressions are allowed:

atom: ('(' [yield_expr|testlist_comp] ')' |    '[' [testlist_comp] ']' |    '{' [dictorsetmaker] '}' |    NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')

The expression corresponding to a list comprehension - testlist_comp looks like the following in Python 3:

testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )

Here, the only statements allowed are

test: or_test ['if' or_test 'else' test] | lambdef
star_expr: '*' expr
comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]

where

comp_if: 'if' test_nocond [comp_iter]
comp_iter: comp_for | comp_if

There is not a single while statement allowed anywhere. The only keywords you are allowed to use is a for, for a for loop.

Solution

Use a for loop, or take advantage of itertools.

like image 38
Akshat Mahajan Avatar answered Sep 21 '22 16:09

Akshat Mahajan