folks,
I want to modify list element with list comprehension. For example, if the element is negative, add 4 to it.
Thus the list
a = [1, -2 , 2]
will be converted to
a = [1, 2, 2]
The following code works, but i am wondering if there is a better way to do it?
Thanks.
for i in range(len(a)):
if a[i]<0:
a[i] += 4
A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
List comprehensions can utilize conditional statement to modify existing list (or other tuples). We will create list that uses mathematical operators, integers, and range (). When we run the above program, the output will be: The list , number_list, will be populated by the items in range from 0-19 if the item's value is divisible by 2.
If you want to change the list in-place, this is almost the best way. List comprehension will create a new list. You could also use enumerate, and assignment must be done to a [i]: Show activity on this post. This version is older, it would work on Python 2.4 For newer versions of Python use conditional expressions as in Adam Wagner or BenH answers
Without list comprehension you will have to write a for statement with a conditional test inside: The return value is a new list, leaving the old list unchanged. The condition is like a filter that only accepts the items that valuate to True.
a = [b + 4 if b < 0 else b for b in a]
If you want to change the list in-place, this is almost the best way. List comprehension will create a new list. You could also use enumerate
, and assignment must be done to a[i]
:
for i, x in enumerate(a):
if x < 0:
a[i] = x + 4
This version is older, it would work on Python 2.4
>>> [x < 0 and x + 4 or x for x in [1, -2, 2]]
0: [1, 2, 2]
For newer versions of Python use conditional expressions as in Adam Wagner or BenH answers
Try this:
b = [x + 4 if x < 0 else x for x in a]
Or if you like map
more than a list comprehension:
b = map(lambda x: x + 4 if x < 0 else x, a)
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