## Tutorial 09: Lists and Loops¶

These notes are adapted from the Python tutorial available at: https://docs.python.org/3/tutorial/.

Here we see method in Python for working with a collection of objects.

### Creating lists¶

We started our Python tutorials by looking at numeric objects and string objects, learning how to create and manipulate such types in Python. Often, we will want to work with an object that contains a collection of numbers or strings. Python knows a number of compound data types, used to group together other values. The most versatile is the list, which we will look at here. (Note: we have already seen lists in the output of re.split, but just did not talk or work with them much).

A list can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type. For example:

In [1]:
squares = [1, 4, 9, 16, 25]
squares


A list of strings:

In [2]:
letters = ["a", "b", "c"]
letters


We will see several types of objects in Python that allow us to collect a number of other objects. Lists are generally considered the most basic of these and will come up frequently in our work.

### Slices of lists¶

Like strings (and all other built-in sequence type), lists can be indexed and sliced:

In [3]:
squares[0]  # indexing returns the item

In [4]:
squares[-1]

In [5]:
squares[-3:]  # slicing returns a new list

Out[5]:
[9, 16, 25]

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:

In [6]:
squares[:]

Out[6]:
[1, 4, 9, 16, 25]

Lists also support operations like concatenation:

In [7]:
squares + [36, 49, 64, 81, 100]

Out[7]:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The built-in function len() applies to lists:

In [8]:
letters = ['a', 'b', 'c', 'd']
len(letters)

Out[8]:
4

A later tutorial will show more compound data types (such as sets, tuples, and dictionaries) as well as more things that we can do with lists. These few starting points, however, will be good to get us started.

### Loops¶

Once we have a list in Python, how can we work with it? Some function take a list as a direct input; we've seen this for example with collections.Counter. If we want to work directly with a list though, we need a way of cycling through all of the elements this is done with a for loop.

Here is the basic syntax of the for loop construct in Python:

In [9]:
for this_letter in letters:
print(this_letter)

a
b
c
d


Let's break this down. Python assigns to the variable this_letter the first element in the list letters, which is just the letter 'a'. It then runs the code print(this_letter), which prints out the letter 'a'. Next, it assigns this_letter to the next elements of letters: 'b' and repeats the same block of code. This continues until we've run the indented code once for each element in the list. The logic here is similar to building a function; we have some indented code that is repeatedly applied with a different assignment to the starting variables.

Here, we can use a for loop to automatically save a list of squares:

In [10]:
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = []

for x in nums:
squares = squares + [x**2]

In [11]:
print(squares)

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


There are a lot of other things we can do with lists, such as list comprehensions, list methods, and iterators. We will see these as instances for using them arise.

## Practice¶

Create a list named my_names containing your given, middle (if you have one) and family name as seperate elements:

In [12]:
my_names = ['Taylor', 'Baillie', 'Arnold']


Write code that prints how how long the list my_names is:

In [13]:
len(my_names)

Out[13]:
3

Construct a new list my_names2 that moves your first name to the end of the list (Note: do this by manipulating my_names, not creating a new list from scratch):

In [14]:
my_names2 = my_names[1:] + [my_names[0]]
print(my_names2)

['Baillie', 'Arnold', 'Taylor']


Take the list of fruits given here:

In [15]:
fruits = ['apple', 'banana', 'pear', 'pineapple', 'grape', 'apricot', 'strawberry']


Use a for loop to create a new list called fruits_cap that contain the capitalized version of each fruit name.

In [16]:
fruits_cap = []
for x in fruits:
fruits_cap = fruits_cap + [x.upper()]

print(fruits_cap)

['APPLE', 'BANANA', 'PEAR', 'PINEAPPLE', 'GRAPE', 'APRICOT', 'STRAWBERRY']