Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 268
tau woobunker Avatar asked Jan 03 '17 02:01

tau woobunker


People also ask

How do you print multiple items in a list Python?

Use * Operator to Print a Python List. Another way to print all of the contents of a list is to use the * or "splat" operator. The splat operator can be used to pass all of the contents of a list to a function.

How do you print multiple variables in Python 3?

To print multiple variables in Python 3, variable names have to enclosed within round brackets and mentioned as comma-separated.

How do I print a specific part of a list in Python?

Use list slicing to print specific items in a list, e.g. print(my_list[1:3]) . The print() function will print the slice of the list starting at the specified index and going up to, but not including the stop index.

How do I print a list in Python 3?

Using the * symbol to print a list in Python. To print the contents of a list in a single line with space, * or splat operator is one way to go. It passes all of the contents of a list to a function. We can print all elements in new lines or separated by space and to do that, we use sep=”\n” or sep=”, ” respectively.


2 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
like image 84
Ashwini Chaudhary Avatar answered Sep 29 '22 19:09

Ashwini Chaudhary


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])
like image 43
TigerhawkT3 Avatar answered Sep 29 '22 19:09

TigerhawkT3