Tuple error?

The following throws the following error when run in python 3 interpreter:

Exception has occurred: AttributeError

‘tuple’ object has no attribute ‘split’

File "C:\dev\Py-1\Test\string_exercises.py", line 47, in <module> author_names = authors.split(",")
authors = "Audre Lorde,Gabriela Mistral,Jean Toomer,An Qi,Walt Whitman,Shel Silverstein,Carmen Boullosa,Kamala Suraiyya,Langston Hughes,Adrienne Rich,Nikki Giovanni"

author_names = authors.split(',')


author_last_names = []
for name in author_names:

code from the error message:

author_names = authors.split(",")

doesn’t match the code you posted:

author_names = authors.split(',')

the error message says authors is a tuple, if i attempt to run the code:


it goes fine. So not sure what goes wrong

Just a small tip in terms of cleanliness, this can be achieved using a simple list comprehension:

author_last_names = [name.split()[-1] for name in author_names]

Thats much more elegant.

let us assume, that the surname of one of the authors is not Williams but Carlos Williams. Than, we will have to use this code:

author_last_names = [i.split()[1:] for i in author_names]

which creates list of lists:

[['Lorde'], ['Carlos', 'Williams'], ['Mistral'], ['Toomer'], ['Qi'], ['Whitman'], ['Silverstein'], ['Boullosa'], ['Suraiyya'], ['Hughes'], ['Rich'], ['Giovanni']]

It creates a problem: how to flatten or break the list of lists? WITHOUT SELF-WRITTEN FUNCTION, but via implemented Python functions! I’ve digged all the internet and found the only slim solution, which, unfortunatelly works only with print:


gives desirable result:

['Lorde'] ['Carlos', 'Williams'] ['Mistral'] ['Toomer'] ['Qi'] ['Whitman'] ['Silverstein'] ['Boullosa'] ['Suraiyya'] ['Hughes'] ['Rich'] ['Giovanni']

but if I try to assign expression to the new variable:

author_last_names_fixed = *author_last_names

it througs the error:

  File "script.py", line 8
    author_last_names_fixed = *author_last_names
SyntaxError: can't use starred expression here
1 Like

Note that the output of print(*author_last_names) is

['Lorde'] ['Carlos', 'Williams'] ['Mistral'] ['Toomer'] ['Qi'] ['Whitman'] ['Silverstein'] ['Boullosa'] ['Suraiyya'] ['Hughes'] ['Rich'] ['Giovanni']

This is simply a sequence of lists; it is not a Python data type that can be assigned to a variable.

The * “operator” is meant to be used within a function call, as you have done with print(); it will not work to simply provide a sequence to assign to a variable.

1 Like