Come straight to the point. A list e.g. lst = [1, 1, 1, 0, 0, 0], now I want to change 1 into 0 as lst = [0, 0, 0, 0, 0, 0].
My original solution likes below:
for item in lst:
if item == 1:
item = 0
Actually, the result list is still lst = [1, 1, 1, 0, 0, 0].
Q1: Is there any other solutions to solve it besides using list comprehension?
Q2: How to write correct list comprehensions when many more if else for in it? So I have tried four styles below:
No.1 lst = [0 if item == 1 for item in lst] # Returns syntax error
No.2 lst = [0 for item in lst if item == 1] # Returns [0, 0, 0]
No.3 lst = [0 if item == 1 else item for item in lst] # Returns [0, 0, 0, 0, 0, 0]
No.4 lst = [0 for item in lst if item == 1 else item] # Returns syntax error
Neither list comprehension nor
for item in iterablemutate the list. In the former case, that’s (practically) impossible by design, in the latter case it’s because Python is pass by value only.You can use a for loop and change values at specific indices. Just don’t to delete or add anything while iterating.
enumerateallows you to have your cake (the item) and eat it (have to index) too.List comprehensions in general are of the form
[expression for target in expression if condition]. The optional filtering part at the end can only skip an item (think of it asif not condition: continue), choosing the item to put into the list being generates happens in the firstexpression– a few versions ago, conditional expressions (expression if condition else expression) were added, so you can do some basic selection in that expression. Doing this twice or more in one expression really pushes it though, so refrain from it for more complex logic.