Reputation: 151
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?
Upvotes: 13
Views: 45441
Reputation: 200
Python's list type does not support that by default. Return a slice object representing the set of indices specified by range(start, stop, step).
class slice(start, stop[, step])
>>>animals[0:5:2]
['bear', 'peacock', 'whale']
Either creating a subclass to implement by yourself or getting specified values indirectly. e.g.:
>>>map(animals.__getitem__, [0,3])
['bear', 'kangaroo']
Upvotes: 2
Reputation: 114320
list(animals[x] for x in (0,3))
is the subset you want. Unlike numpy arrays, native Python lists do not accept lists as indices.
You need to wrap the generator expression in list
to print it because it does not have an acceptable __str__
or __repr__
on its own. You could also use str.join
for an acceptable effect: ', '.join(animals[x] for x in (0,3))
.
Upvotes: 7
Reputation: 250961
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
Upvotes: 10
Reputation: 49318
Slicing with a tuple as in animals[0,3]
is not supported for Python's list
type. If you want certain arbitrary values, you will have to index them separately.
print(animals[0], animals[3])
Upvotes: 9