nos
nos

Reputation: 20880

modify list element with list comprehension in python

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

Upvotes: 16

Views: 30558

Answers (5)

kennytm
kennytm

Reputation: 523784

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

Upvotes: 8

Blender
Blender

Reputation: 298582

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)

Upvotes: 2

Facundo Casco
Facundo Casco

Reputation: 10603

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

Upvotes: 3

BenH
BenH

Reputation: 2120

a = [b + 4 if b < 0 else b for b in a]

Upvotes: 25

Adam Wagner
Adam Wagner

Reputation: 16127

Why mutate, when you can just return a new list that looks like you want it to?

[4 + x if x < 0 else x for x in [1, -2, 2]]

Upvotes: 2

Related Questions