0

in Python how to increment the values in a list without having to write a for loop, e.g.:

group  = [0]*3
item   = [1,2,3]
group += item
print group

to get group = [1,2,3] instead of group = [0,0,0,1,2,3] ?

3

2 Answers 2

2

You could use numpy module. This won't need a for loop.

>>> import numpy as np
>>> group  = np.array([0]*3)
>>> item   = np.array([1,2,3])
>>> group += item
>>> group
array([1, 2, 3])
>>> list(group)
[1, 2, 3]
Sign up to request clarification or add additional context in comments.

Comments

1

You can do element-wise operations (addition in this case) by using zip within a list comprehension.

>>> group = [0]*3
>>> item   = [1,2,3]
>>> group = [i + j for i,j in zip(group, item)]
>>> group
[1, 2, 3]

This is a general solution if group didn't start out as all zeroes, and you wanted to add the current values with some new values.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.