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?
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.
To print multiple variables in Python 3, variable names have to enclosed within round brackets and mentioned as comma-separated.
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.
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.
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
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With