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]))
Answers:
L = ["One", "Two", "Three", "Four", "Five"]
for elem in L:
print(f"{elem},{len(elem)}")
This code should achieve what you are looking for.
L = ["One", "Two", "Three", "Four", "Five"]
for item in L:
print(item, len(item), sep=",")
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)}")
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))
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.
This is the code I have tried
L=["One","Two","Three","Four","Five"]
for i in L:
print(i,len(L[i]))
L = ["One", "Two", "Three", "Four", "Five"]
for elem in L:
print(f"{elem},{len(elem)}")
This code should achieve what you are looking for.
L = ["One", "Two", "Three", "Four", "Five"]
for item in L:
print(item, len(item), sep=",")
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)}")
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))
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.