Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to know/show the indices in a python list?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading