0

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?

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

enumerate(iterable) yields an index, element tuple. Better than range(len(iterable)) when you need both the index and the element.
@brunodesthuilliers, Thank you for comment. I added that as an alternative.
"loop control variable" is an odd thing to call it. x is the items from the list. If x was mutable, the normal thing is for *= to mutate in place. However int is immutable so it just creates a new int object and rebinds instead.
@gnibbler, Thank you for comment. I fixed it. BTW, I saw the loop control variable here.
1

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]

3 Comments

I don't want to look picky though the extra whitespaces are not needed in the second example. See python.org/dev/peps/pep-0008/… If it looks messy we can write something from new line or put some nested operations into separate expression/function.
For this case (multiply by 2), you may find x + x is a little faster than x * 2
@gnibbler Right. On my box I gain around 9% of execute time. But I think this has nothing to do with OP's question.
1

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)

2 Comments

Which works only in python2.x and OP asked explicitly about 2 and 3.
OK in Python 3 for the map() case we can do list(map(func, seq)). This is just an idea of different ways.
1

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.

1 Comment

Oh, great! This will be very useful. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.