0

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.