What are some important differences between a string and a list?

Question

What are some important differences between a string and a list in Python?

Answer

Strings and lists share many similarities as we have seen throughout this lesson. However, strings are not interchangeable with lists because of some important differences.

Strings can only consist of characters, while lists can contain any data type.

Because of the previous difference, we cannot easily make a list into a string, but we can make a string into a list of characters, simply by using the list() function.

message = "Hello"
message_to_list = list(message)

print(message_to_list)
# message_to_list is now ['H', 'e', 'l', 'l', 'o']

Furthermore, when we add to a string, we use the + concatenation operator to do so. With a list, we use the .append() method to add elements.

Finally, one of the most important differences is mutability. Strings are immutable, meaning that we cannot update them. We could update values in a list however quite easily.

# This will result in this error message:
# TypeError: 'str' object does not support item assignment
name = "Joe"
name[0] = "P"

# For lists, we can easily update an element
name_as_list = ["J", "o", "e"]
name_as_list[0] = "P"
# name_as_list is now ["P", "o", "e"]

6 Likes

4 posts were split to a new topic: I don’t understand the loop in the review

5 posts were split to a new topic: Password_generator explained

2 posts were split to a new topic: Is this also a move to the right?

2 posts were split to a new topic: Why does this not add additional strings

thank you for clarifying the difference between list and string