Lists: How to print out element indices to console in Python

Hello,
How do you print to console all the elements indices? I can print out individual index but I would like to print out all elements in list.

my_list = [‘red’, ‘blue’, ‘purple’, ‘yellow’, ‘green’, ‘orange’].

Example #1: to print out individual index (print(my_list[3]). The output would be ORANGE.
I would like to print all all indices at once.
Thank you.

Double check your terminology as I may be a little confused here. If you just want to print all the elements in your list (the contents of the list) then print(my_list) should be about right.

If you actually want the indices (e.g. 0, 1, 2, 3) then perhaps range(len(my_list)) might be a simple solution.

that would output the below, i would like output to show 0,1,2,3,4,5

my_list = [‘red’, ‘blue’, ‘purple’, ‘yellow’, ‘green’, ‘orange’]

print(range(len(my_list)))
range(0, 6)

I’m not certain why it happens but if you do:

lst = ['a', 'b', 'c']
print(range(len(lst))

You end up getting range(0, 3) printed to the console. Certainly a good thing to do some research on, and out of curiosity I probably will later. The only way I know to see each individual item in a range() is converting it to a list first:

lst = ['a', 'b', 'c']

print(list(range(len(lst))))

Or by using a for loop:

lst = ['a', 'b', 'c']

for i in range(len(lst)):
  print(i)

Though I’m not certain you have learned about loops yet.

1 Like

It’s because in Python3 range is a bit of a special case. It returns an iterable range object (an immutable, low memory sequence-like object). It’s not an iterator, it can’t be exhausted and it supports certain actions common to sequences like slicing and containment testing but not others. The docs have some nice examples-
https://docs.python.org/3/library/stdtypes.html#range

@8-bit-gaming’s advice to create a different sequence such as a list for printing is a good option, as is looping (though you might need to pass extra arguments to print in order to get the exact output you mentioned). Unpacking with * is another option if you’ve come across it before and the sep parameter would allow you alter the output further if you needed to.

2 Likes