daniel
daniel

Reputation: 1978

Python list element syntax

I'm new to python and I want to use the syntax

a = [3, 6]
for x in a:
    x *= 2

so 'a' would be [6, 12]

...but this doesn't seem to work. How should I write the code, as simple as possible, to get the wanted effect?

Upvotes: 0

Views: 97

Answers (4)

falsetru
falsetru

Reputation: 369044

The following code change creates a new int object and rebinds x, and not changes the items of the list.

for x in a:
    x *= 2

To change the item of the list you should use a[..] = ...

for i in range(len(a)):
    a[i] *= 2

You can also use List comprehension as the answer of @Hyperboreus.

To change the value of the nested list, use nested loop.

for i in range(len(a)):
    for j in range(len(a[i]):
        a[i][j] *= 2

Alternative that use enumerate.

for i, x in enumerate(a):
    a[i] = x * 2

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304137

If you find you need to do a lot of these things, maybe you should use numpy

>>> import numpy as np
>>> a = np.array([3, 6])
>>> a *= 2
>>> a
array([ 6, 12])

2 (or more) dimensional array works the same

>>> a = np.array([[3, 6],[4,5]])
>>> a *= 2
>>> a
array([[ 6, 12],
       [ 8, 10]])

But there is an overhead converting between list and numpy.array, so it's only worthwhile (efficiency wise) if you need to do multiple operations.

Upvotes: 1

Eugene Naydenov
Eugene Naydenov

Reputation: 7295

You can use either list comprehension or map() function.

my_list = [3, 6]
my_list = [x * 2 for x in my_list]

my_list = [3, 6]
my_list = map(lambda x: x * 2, my_list)

Upvotes: 1

Hyperboreus
Hyperboreus

Reputation: 32429

You can use this:

a = [x * 2 for x in a]

And for a nested list:

a = [ [1,2,3], [4,5,6] ]
a = [ [x * 2 for x in x] for x in a]

Upvotes: 1

Related Questions