I have problems with identifying/knowing the indices of a python list. I have a variable, say """book="The Hitchhker’s Guide to the Galaxy"""; and want to turn it into a list by mlist=list(book). To get the indices of every one of the elements in my list, I used the code as I got in the link how list indices work!
book="The Hitchhker's Guide to the Galaxy"
mlist=list(book)
for i in enumerate(mlist):
print(i,mlist)
However, the result was a long list of results as I present you a part of it here:
(0, 'T') ['T', 'h', 'e', ' ', 'H', 'i', 't', 'c', 'h', 'h', 'k', 'e', 'r', "'", 's', ' ', 'G', 'u', 'i', 'd', 'e', ' ', 't', 'o', ' ', 't', 'h', 'e', ' ', 'G', 'a', 'l', 'a', 'x', 'y']
(1, 'h') ['T', 'h', 'e', ' ', 'H', 'i', 't', 'c', 'h', 'h', 'k', 'e', 'r', "'", 's', ' ', 'G', 'u', 'i', 'd', 'e', ' ', 't', 'o', ' ', 't', 'h', 'e', ' ', 'G', 'a', 'l', 'a', 'x', 'y']
(2, 'e') ['T', 'h', 'e', ' ', 'H', 'i', 't', 'c', 'h', 'h', 'k', 'e', 'r', "'", 's', ' ', 'G', 'u', 'i', 'd', 'e', ' ', 't', 'o', ' ', 't', 'h', 'e', ' ', 'G', 'a', 'l', 'a', 'x', 'y']
(3, ' ') ['T', 'h', 'e', ' ', 'H', 'i', 't', 'c', 'h', 'h', 'k', 'e', 'r', "'", 's', ' ', 'G', 'u', 'i', 'd', 'e', ' ', 't', 'o', ' ', 't', 'h', 'e', ' ', 'G', 'a', 'l', 'a', 'x', 'y']
(4, 'H') ['T', 'h', 'e', ' ', 'H', 'i', 't', 'c', 'h', 'h', 'k', 'e', 'r', "'", 's', ' ', 'G', 'u', 'i', 'd', 'e', ' ', 't', 'o', ' ', 't', 'h', 'e', ' ', 'G', 'a', 'l', 'a', 'x', 'y']
(5, 'i') ['T', 'h', 'e', ' ', 'H', 'i', 't', 'c', 'h', 'h', 'k', 'e', 'r', "'", 's', ' ', 'G', 'u', 'i', 'd', 'e', ' ', 't', 'o', ' ', 't', 'h', 'e', ' ', 'G', 'a', 'l', 'a', 'x', 'y']
And list goes on and on until it reaches the last element.
My question is, how is it possible to have the indices printed with a really simple and clear form without any elaboration like my result presented.
>Solution :
for index, item in enumerate(list):
print(f"{item} at index {index}")
In Python the enumerate built-in class (when calling it you are calling the constructor) works this way:
>>> enumerate['item1', 'item2'] # creates the equivalent to [(0, 'item1'), (1, 'item2')]