More loops

Below are a few more useful things to know when working with loops and iterable objects like lists. It uses the raw_data = '13839' example that we have been trying to break into a list of integers.

First, I coded

for i in range(len(list_data)):
    list_data[i] = int(list_data[i])

which does what we want. It produces a list of integers.

In [1]:
raw_data = '13839'
list_data = list(raw_data)

for i in range(len(list_data)):
    list_data[i] = int(list_data[i])
[1, 3, 8, 3, 9]

Getting stuck

Some people would naturally start by looping over the list objects...

for obj in list_data:

but were then stuck. How do I get the int(obj) saved to a list?

Get the index and the value at the same time

The enumerate() function (docs). Enumerate takes an iterable object as an argument and returns a tuple of the index and the value.

In [4]:
for i, obj in enumerate(list_data):
    print('The index is', i, 'and the value is', obj)
The index is 0 and the value is 1
The index is 1 and the value is 3
The index is 2 and the value is 8
The index is 3 and the value is 3
The index is 4 and the value is 9
In [5]:
raw_data = '13839'
list_data = list(raw_data)

for i, datum in enumerate(list_data):
    list_data[i] = int(datum)
[1, 3, 8, 3, 9]

Saving to a different list

You may not want to overwrite list_data with the integers, but rather save them in a separate list.

To do this, we first create an empty list modified_data=[] and then use the .append() list method to add elements to the end of the list.

In [6]:
list_data = list(raw_data)
print('The string list', list_data)

modified_data = []     # an empty list
for datum in list_data:

print('The integer list', modified_data)
The string list ['1', '3', '8', '3', '9']
The integer list [1, 3, 8, 3, 9]