2

I tried this following code but it has not worked so far it says that I cannot

names = ['John Johnson Doe', 'Jane Janis Doe']
firstnames = []

for name in names:
     firstnames.append(names[name].split(' ')[0])
print(firstnames)

The error I am getting here is:

TypeError: list indices must be integers or slices, not str
Noah Broyles
  • 621
  • 1
  • 7
  • 21
  • 1
    can you add the output that you're expecting please – baxx Mar 28 '20 at 18:41
  • Link to [Accessing and Working with Python Lists](https://www.tutorialspoint.com/python/python_lists.htm) – CannedScientist Mar 28 '20 at 18:45
  • Does this answer your question? [Accessing the index in 'for' loops?](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – Brian Mar 28 '20 at 21:33

3 Answers3

5

The variable name contains the content of the list names, not the indices. So in the first iteration name = 'John Johnson Doe' and you are trying to use it as an index for names, i.e. you're doing names['John Johnson Doe'].

Just do the split on name instead of names[name] and all will work properly.

hmhmmm
  • 173
  • 4
2

You can create firstnames directly

names = ['John Johnson Doe', 'Jane Janis Doe']

Then

firstnames = [n.split(' ')[0] for n in names]

firstnames
['John', 'Jane']
baxx
  • 1,902
  • 15
  • 34
2

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)
abhiarora
  • 7,515
  • 3
  • 27
  • 46