Time for yet another article on data type conversions. If you haven’t done so yet, make sure to read my previous articles as well:
– String to Number Conversions
– Converting String Representations of Binary, Octal and Hexadecimal Integers
– Number to String Conversions
Today we’ll learn how to convert strings to lists.
Here’s the video version of this article:
You can enter more than one thing at a time in user input. You can enter a list:
>>> colors = input("What are your favorite colors?")
What are your favorite colors?
["green", "yellow", "blue"]
If you echo the input, it will appear in quotes as a string.
>>> colors
'["green", "yellow", "blue"]'
There will be no quotes if you use the print function, but still a string is returned.
>>> print(colors)
["green", "yellow", "blue"]
You can easily check what type something is by means of the type function. It turns out that colors is a string:
>>> type(colors)
<class 'str'>
Raw Input vs Evaluated Input
If you want a list to be returned, you can cast the input to a list by using the list function or use the eval function. The eval function is used to evaluate input. So, what we get with just input is the so-called raw input, which is a string. What we get with eval(input()) is evaluated input. There’s a difference in how these two functions work. First let’s use the list function:
>>> cities = list(input("What cities did you go to?"))
What cities did you go to?
['Rome', 'Venice', 'Florence']
Now we have a list of all the characters:
>>> cities
['[', "'", 'R', 'o', 'm', 'e', "'", ',', ' ', "'", 'V', 'e', 'n', 'i', 'c', 'e', "'", ',', ' ', "'", 'F', 'l', 'o', 'r', 'e', 'n', 'c', 'e', "'", ']']
>>> type(cities)
<class 'list'>
And this is what we get using the eval function:
>>> cities = eval(input("What cities did you go to?"))
What cities did you go to?
['Rome', 'Venice', 'Florence']
This is the list that we get now. This is the one we were expecting:
>>> cities
['Rome', 'Venice', 'Florence']
Now we have a list, too.
>>> type(cities)
<class 'list'>