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 obtain the number of single character for each item contained withing a object

I am trying using a for loop to count the characters within this object:

S = "Hello World"
d = S.split()
d
['Hello', 'World']

for i in (0,len(d)):
    print(len(d[i]))

However, I got the following error.

Traceback (most recent call last):
  File "<pyshell#26>", line 2, in <module>
    print(len(n[i]))
IndexError: list index out of range

Could anyone explain where this error come from and how to possibly fix it?

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

>Solution :

len() reports the length of the list – if there is 1 item in the list, it is of length 1 — the index of that element is 0.

len(['one element']) == 1

Indexing is 0 based:

 k = ['one element']
 k[0] == "one element"

You use a tuple of (0, len(d)): len(d) is 1 bigger then the biggest possible index of your list because indexing starts at 0.

for i in (0,len(d)):    # (0,2)
    print(len(d[i]))    # d[2] is out of index

Hence: list index out of range

Use range(len(d)) instead – or even better:

for element in d:
    print(len(element))   # to print all
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