I recently published a couple articles on data type conversions. If you would like to read them, here they are:
– String to Number Conversions
– Converting String Representations of Binary, Octal and Hexadecimal Integers
– Number to String Conversions
Today we’ll be talking about sequence conversions. In particular we’ll learn how to convert any sequence to a list or tuple.
Here’s the video version of this article:
Any sequence to list
We can convert any sequence to a list by using the list function:
– string to list:
>>> s = "hello"
>>> list(s)
['h', 'e', 'l', 'l', 'o']
– tuple to list:
>>> tup = (3, "OK", 7.8, "yes")
>>> list(tup)
[3, 'OK', 7.8, 'yes']
– range to list:
>>> rng = range(8)
>>> list(rng)
[0, 1, 2, 3, 4, 5, 6, 7]
Any sequence to tuple
We can also convert any sequence to a tuple by using the tuple function:
– string to tuple:
>>> str = "hello"
>>> tuple(str)
('h', 'e', 'l', 'l', 'o')
– list to tuple:
>>> lst = [3, "OK", 7.8, "yes"]
>>> tuple(lst)
(3, 'OK', 7.8, 'yes')
– range to tuple:
>>> rng = range(8)
>>> tuple(rng)
(0, 1, 2, 3, 4, 5, 6, 7)