In [1]:
# demo from class on 2015-09-02
# objective: how do we convert a list of integer values into a list of equivalent string values?
# in other words, how do we convert each element in a list to a different data type?
# first, let's make a list containing the first 5 even numbers
int_list = [2, 4, 6, 8, 10]
In [2]:
# how many elements are in our list?
len(int_list)
Out[2]:
In [3]:
# what is the value of the element in the zero-th position of the list?
int_list[0]
Out[3]:
In [4]:
# what is the data type of this element in the zero-th position?
type(int_list[0])
Out[4]:
In [5]:
# let's convert that element from an int to a string using the str() function
str(int_list[0])
Out[5]:
In [6]:
# let's check the data type that results from that str() function operating on our list element
type(str(int_list[0]))
Out[6]:
In [7]:
# now we'll create a new list to contain the string versions of our integers
str_list = []
In [8]:
# now let's convert the element in the zero-th position of our int_list to a string
# and append it to the new str_list that will contain string values
# remember, the way to add a new element to a list is list.append()
# we are simply appending the result of the string conversion
str_list.append(str(int_list[0]))
In [9]:
# our str_list should have one element - the value at the zero-th position of int_list, converted to a string
str_list
Out[9]:
In [10]:
# looks like that worked, so let's convert and append the rest of the values
# we know our int_list contains 5 elements from when we ran len() on it earlier
# we've already done position 0, now let's do positions 1 - 4
str_list.append(str(int_list[1]))
str_list.append(str(int_list[2]))
str_list.append(str(int_list[3]))
str_list.append(str(int_list[4]))
In [11]:
# let's see our list of strings
str_list
Out[11]:
In [12]:
# and for comparison, here's our original list of integers
int_list
Out[12]:
In [13]:
# what we have seen is a manual way of doing this int -> string conversion
# the whole benefit of coding is that we automate this sort of manual work
# over the next couple of weeks we'll learn more advanced and efficient techniques like this:
new_list = []
for value in int_list:
new_list.append(str(value))
new_list
Out[13]:
In [14]:
# ...and eventually we'll learn even more advanced/efficient techniques, like this:
[ str(value) for value in int_list ]
Out[14]:
In [ ]: