I'm trying to add different words from a list to lines in order. However, I am stuck with it. Can you please tell me how to proceed? I am getting a type error, and couldn't get my output.
The output that I'm trying to get:
it starts with: one or more.
it starts with: two or more.
it starts with: three or more.
The code that I tried:
a=["one","two","three"]
for i in a:
print("it starts with: " a[i] "or more")
The result I'm getting:
TypeError: list indices must be integers or slices, not str
CodePudding user response:
i
is already the element you want.
In Python the expression for i in a
assigns elements of the array a
to the variable i
on every pass of the loop. You don't nedd to address the elements.
for i in a:
print("it starts with: " i "or more")
CodePudding user response:
So the issue you're encountering is that when you tell python to take an element 'i' from the list the 'i' value is not the index but rather the value. So basically what your code is doing is a["one"] which doesn't work. If you replace a[i] with just i it should work. Also I would recommend replacing ' ' with ',' for there to be a space between your two strings and the value you're taking from a.
CodePudding user response:
i already represents each element in the list. You can use an f-string to put it into the string:
for i in a:
print(f"it starts with: {i} or more")