Home > other >  how to obtain the number of single character for each item contained withing a object
how to obtain the number of single character for each item contained withing a object

Time:03-12

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?

CodePudding user response:

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
  • Related