Answer a question

I have created a list and want to choose a handful of items to print from the list. Below, I'd just like to print out "bear" at index 0 and "kangaroo" at index 3. My syntax is not correct:

>>> animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
>>> print (animals[0,3])

Traceback (most recent call last): File "", line 1, in print (animals[0,3]) TypeError: list indices must be integers or slices, not tuple

I tried with a space between the indexes but it still gives an error:

>>> print (animals[0, 3])

Traceback (most recent call last): File "", line 1, in print (animals[0, 3]) TypeError: list indices must be integers or slices, not tuple

I am able to print a single value or a range from 0-3, for example, with:

>>> print (animals [1:4])
['python', 'peacock', 'kangaroo']

How can I print multiple non-consecutive list elements?

Answers

To pick arbitrary items from a list you can use operator.itemgetter:

>>> from operator import itemgetter    
>>> print(*itemgetter(0, 3)(animals))
bear kangaroo
>>> print(*itemgetter(0, 5, 3)(animals))
bear platypus kangaroo
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐