How to print multiple non-consecutive values from a list with Python 3.5.1

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']

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])

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)).


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