The error message:
TypeError: function expected string, got list
occurs when a function expects a string (str
) as an argument but receives a list (list
) instead.
1. Causes and Solutions
Cause 1: Passing a List Instead of a String to a String Function
Some string functions work only with strings and will not accept a list.
Incorrect Code:
text = ["Hello", "World"]
print(text.lower()) # TypeError: 'list' object has no attribute 'lower'
Solution: Apply lower()
to Each String in the List
text = ["Hello", "World"]
lowercase_text = [word.lower() for word in text]
print(lowercase_text) # Output: ['hello', 'world']
Cause 2: Passing a List to strip()
, replace()
, or Other String Methods
String methods like strip()
, replace()
, and split()
expect a string, not a list.
Incorrect Code:
words = ["hello ", " world "]
print(words.strip()) # TypeError: 'list' object has no attribute 'strip'
Solution: Apply the Method to Each String in the List
words = ["hello ", " world "]
clean_words = [word.strip() for word in words]
print(clean_words) # Output: ['hello', 'world']
Cause 3: Using join()
Incorrectly
The join()
method expects a list of strings, but sometimes a list of lists or numbers is passed.
Incorrect Code:
words = ["Hello", "World"]
sentence = "-".join(words, "!") # TypeError: join() takes exactly one argument (2 given)
Solution: Pass Only One List Argument
words = ["Hello", "World"]
sentence = "-".join(words) # Works fine
print(sentence) # Output: Hello-World
Cause 4: Passing a List Instead of a String to open()
The open()
function expects a filename as a string, not a list.
Incorrect Code:
file_names = ["data.txt"]
file = open(file_names, "r") # TypeError: expected str, bytes or os.PathLike object, not list
Solution: Use a String Instead
file_name = "data.txt"
file = open(file_name, "r") # Works fine
Cause 5: Passing a List Instead of a String to int()
The int()
function expects a string representation of a number, not a list.
Incorrect Code:
num_list = ["123"]
number = int(num_list) # TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
Solution: Extract the String from the List
number = int(num_list[0]) # Works fine
print(number) # Output: 123