Lists

Overview

Lists are one of the most commonly used data types in Python. Some of the additional functionality covered in the following sections on this page help to illustrate why lists are so commonly used. While ( are almost always associated with tuples square brackets [ are the domain of lists:

my_list = [1,2,3,4,5.5, "some_text"]

Lists are mutable meaning they can be muted…​ disregard that. Lists are mutable meaning that they can be changed after the list has initially been declared. This is notable different from the tuples which are immutable.

my_list = [1,2,3,"i_can_be_muted"]
my_list[3] = "still_not_the_right_word"
print(my_list)
[1,2,3,'still_not_the_right_word']

Just like tuples you can convert between the two types easily:

lex_listor = [1,2,3] # I'm a list
super_tuple = tuple(lex_listor)
print(type(super_tuple))
<class 'tuple'>

Indexing

R and Python are similar in a lot of ways. One key distinction to understand is how they index values. Python is 0-indexed where as R is 1-indexed. What does this mean? In practice in means that the placement of items in R always starts with 1. In comparison Python will always start with a 0. It’s a little easier to understand in an example:

my_r_list <- c("first", "second", "third", "fourth")

In this case since we are looking at R code the list indexing is:

["first", "second", "third", "fourth"]
[   1,        2,        3,        4  ]

So if we wanted to access the "third" entry we could run:

my_list[3]

However, in Python the same list is 0-indexed. An example is included below for comparison:

my_list = ["first", "second", "third", "fourth"]
["first", "second", "third", "fourth"]
[   0         1        2         3   ]

If we wanted to get the "third" entry in the list we would use the code snippet below:

my_list[2]

Thankfully some of the syntax is the same between Python and R. For example, the : continues to hold the same functionality between both languages (as long as you remember the index difference):

In R:

my_list[1:2]
"first", "second"

In Python:

my_list[0:2]
"first", "second"

Python also supports a second : that indicates a "jump":

my_list[0:3:2]
"first", "third"

Sadly Python and R do differ in other ways. One major difference is how the two languages handle negative indexes. In R, they remove a value at the given position:

my_list[c(-1,-2)]
"third", "fourth"

In Python, negative indexes just mean "start from the back of the list" instead of "start from the front". For example:

my_list[-1]
"fourth"

Negative indexes can be a little confusing in Python because while positive indexes are 0-indexed negative indexes are not (not sure what -0 is). This means that my_list[-4] is valid. In this case it would return "first". However if you tried to print my_list[4] it would produce an IndexError because the last list value is my_list[3]. Don’t worry if this is a bit confusing at first. It gets easier as you write more Python code.

List Methods

A method is a function for a particular object. When you hear or read method you can just think function. A list in this case is an example of an object that you can run methods on. In Python, the most common objects like lists, dicts, tuples, sets, etc., all have extremely useful methods built right in!

The following is a table of list methods from w3schools.

Method Description

append()

Adds an element at the end of the list

clear()

Removes all the elements from the list

copy()

Returns a copy of the list

count()

Returns the number of elements with the specified value

extend()

Add the elements of a list (or any iterable), to the end of the current list

index()

Returns the index of the first element with the specified value

insert()

Adds an element at the specified position

pop()

Removes the element at the specified position

remove()

Removes the item with the specified value

reverse()

Reverses the order of the list

sort()

Sorts the list

We can demonstrate some of these methods in the examples below. Let’s start by creating a few lists that we can use:

list_one = ["first", "second", "third", "fourth", "fifth"]
list_two = ["sixth", "seventh", "eighth", "ninth"]

What if we wanted to add the string "tenth" to list_two?

list_two.append("tenth")
print(list_two)
["sixth", "seventh", "eighth", "ninth", "tenth"]

Ok, but what if I wanted to remove fourth from list_one and then add it back?

list_one.remove("fourth") # First we can remove it.
print(list_one)
list_one.append("fourth") # Then we can add it back.
print(list_one)
["first", "second", "third", "fifth"]
["first", "second", "third", "fifth", "fourth"]

Notice that adding fourth back to the list changes its index place. In this case it goes from an index of 3 in the original list to 4 in the new list.

What if we wanted to remove the first element and save it in a new variable?

new_variable = list_one.pop(0)
print(f'The new variable: {new_variable}')
print(f'The old list: {list_one}')
The new variable: first
The old list: ["second", "third", "fourth", "fifth"]

These are awesome, but what if I wanted to combine the two lists into one big list?

list_one.extend(list_two)
print(list_one)
['second', 'third', 'fifth', 'fourth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth']

List Comprehensions

Another great feature of lists in Python is the idea of list comprehensions. These allow for the concise creation of list objects and can include logic such as for and if statements. Lists aren’t the only object type that has comprehensions in Python (dict comprehensions are very helpful), but they are the most common.

For the first example lets say that we wanted to create a list of all event numbers between 1 and 10. We could do this via a for loop:

blank_list=[]
for i in range(1, 11):
    if i % 2 == 0:
        blank_list.append(i)
print(blank_list)
[2,4,6,8,10]

This works well and will give us the output that we’d expect. However, we could also write this with a list comprehension:

blank_list = [i for i in range(1,11) if i % 2 == 0]
print(blank_list)
[2,4,6,8,10]

The comprehension follows the same logic as our original for loop above, but it is much more concise. List comprehensions can get pretty complex and allow for nesting and function calls. You’ll also see lots of code examples that utilize list comprehensions so they are definitely worth knowing.