What are some important differences between a string and a list in Python?
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
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 = "P" # For lists, we can easily update an element name_as_list = ["J", "o", "e"] name_as_list = "P" # name_as_list is now ["P", "o", "e"]