Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 318
nos Avatar asked Dec 16 '11 17:12

nos


People also ask

What is list comprehension in Python?

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.

How to modify an existing list using list comprehensions?

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.

How to change a list in place in Python?

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

How to return a value from a list without list comprehension?

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.


4 Answers

a = [b + 4 if b < 0 else b for b in a]
like image 193
BenH Avatar answered Oct 20 '22 15:10

BenH


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
like image 35
kennytm Avatar answered Oct 20 '22 13:10

kennytm


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

like image 3
Facundo Casco Avatar answered Oct 20 '22 15:10

Facundo Casco


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)
like image 2
Blender Avatar answered Oct 20 '22 13:10

Blender