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.
Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.
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.
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.
List comprehensions are great because they require less lines of code, are easier to comprehend, and are generally faster than a for loop.
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()]
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.
Use a for
loop, or take advantage of itertools
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With