Reputation: 87
So, I got this list called otherlist
and I would like to add a few objects from list1
. The thing is that I only got their order number, not the actual value of the numbers. For example:
otherlist.append(list1[a,a+20,a+20*2,a+20*3])
(where a
is a changing number)
Yeah as you may have noticed we want ever 20th number in the list.
How to do so. I get the error message: TypeError: list indices must be integers, not tuple
Upvotes: 0
Views: 650
Reputation: 250871
Use list.extend
with a generator expression:
my_list.extend(list1[a + 20*i] for i in range(4))
Demo:
>>> lis = []
>>> list1 = range(1000)
>>> a = 2
>>> lis.extend(list1[a + 20*i] for i in range(4))
>>> lis
[2, 22, 42, 62]
Upvotes: 3
Reputation: 1121196
Python list
indices cannot be tuples (comma-separated indices); you can only index one value at a time.
Use operator.itemgetter()
to get multiple indices:
from operator import itemgetter
otherlist.extend(itemgetter(a, a + 20, a + 20 * 2, a + 20 * 3)(list1))
or use a generator expression:
otherlist.extend(list1[i] for i in (a, a + 20, a + 20 * 2, a + 20 * 3))
or even
otherlist.extend(list1[a + 20 * i] for i in range(4))
Note that I used list.extend()
to add individual values to otherlist
, so that it grows by 4 elements.
Upvotes: 3