The error I am getting here is TypeError: list indices must be integers or slices, not str
The TypeError exception thrown by python interpreter cleary says that you were trying to use a str
object as an index in your list. It means variable name
is a str
in your program. I think you were assuming it to be an int
.
The Python for statement iterates over the members of a sequence in order, executing the block (code under for loop) each time.
Your loop variable name
will be referning to one of the object in your list names
in each of it's iteration. It doesn't hold an index to an object in the sequence.
I am assuming you want the first name of every string present in your list names
. Here's how you should do it with list comprehensions,
print([n.split(' ')[0] for n in names])
However, I have rectified your code as well. Try this:
names = ['John Johnson Doe', 'Jane Janis Doe']
firstnames = []
for name in names:
firstnames.append(name.split(' ')[0])
print(firstnames)
Outputs:
['John', 'Jane']
If you still want the indexes
, then you can have a look at enumerate, try this:
names = ['John Johnson Doe', 'Jane Janis Doe']
firstnames = []
for ndx,name in enumerate(names):
firstnames.append(names[ndx].split(' ')[0])
print(firstnames)