how do I write a program to print the length of each element in a list in this format 'One,3'

Question:

This is the code I have tried

L=["One","Two","Three","Four","Five"]
for i in L:
  print(i,len(L[i]))
Asked By: Vivek Kumar Vinay

||

Answers:

L = ["One", "Two", "Three", "Four", "Five"]
for elem in L:
    print(f"{elem},{len(elem)}")
Answered By: bitflip

This code should achieve what you are looking for.

L = ["One", "Two", "Three", "Four", "Five"]
for item in L:
    print(item, len(item), sep=",")
Answered By: kesetovic

You almost had it. When you use for loops in Python such as for i in L:, the variable i is the item in the list, not the index. This means you need to do len(i) instead of len(L[i]). I’ve added code below that does what you want, using more descriptive variable names. Also, I used f-strings to format the output.

numbers = ["One", "Two", "Three", "Four", "Five"]
for number in numbers:
    print(f"{number},{len(number)}")
Answered By: Jack Taylor

In your code you are loop through elements of the list not the index of the elements of list. Therefor i is the element not the index. Therefore in first loop L[i] equals to L["One"] that is wrong because index must be a number. Change the code as follows then it will work.

L=["One","Two","Three","Four","Five"]
for i in L:
      print(i,len(i))
Answered By: YJR

Try foing it this way,

for i in L:
  print(i,len(I))

because when you did it your trying to ask the list to find the index i but it was not possible.

Answered By: Sai Santosh Pal
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.