Back To Index

IntroLosts

# Lists¶

### Basics and reading from lists¶

One of the basic ubiquitous data structures in Python is its built-in list structure. They can be treated as arrays, linked lists, or queues. List literals are marked with square brackets [ ] and are indexed starting at 0.

In [91]:
myList1 = [1,2,3,4] #initialize a list (This is a comment)

In [92]:
myList1[1] #look at the element at index 1

Out[92]:
2

The length of the list can be fetched using the len( ) function

In [93]:
len(myList1)

Out[93]:
4

The right end of the list can be accessed using negative indices, starting with -1, proceeding backwards.

In [94]:
myList1[-1], myList1[-2]

Out[94]:
(4, 3)

Like arrays in other languages, we have to be careful to not read off end of the list, both for positive and negative indices.

In [95]:
myList1[3] #last item (Equal to List1[-1])

Out[95]:
4
In [96]:
myList1[4] #Attempt to read off right the end of the list

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-96-acedc92f611b> in <module>
----> 1 myList1[4] #Attempt to read off right the end of the list

IndexError: list index out of range
In [97]:
myList1[-4] #first item in the list (equal to List1[0])

Out[97]:
1
In [98]:
myList1[-5] #Attempt to read off left the end of the list using a negative index

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-98-d1248979228a> in <module>
----> 1 myList1[-5] #Attempt to read off left the end of the list using a negative index

IndexError: list index out of range

### Writing to lists and extending them¶

List entries can be overwritten (formally, they are “mutable”)

In [99]:
#Assign value 5 to fourth element of the List
myList1[3]=5

In [100]:
myList1

Out[100]:
[1, 2, 3, 5]

Lists can contain anything and can have mixed types and can including other lists.

In [101]:
someList2 = [4, True, "Dog", myList1]

In [102]:
someList2 #look at the contents of someList2

Out[102]:
[4, True, 'Dog', [1, 2, 3, 5]]

Lists can be made longer (they’re extensible), or insert items

In [103]:
myList1.append(6)

In [104]:
myList1

Out[104]:
[1, 2, 3, 5, 6]
In [105]:
myList1.insert(2,9) #inserts a 9 at index 2, pushing the rest of the list back.

In [106]:
myList1

Out[106]:
[1, 2, 9, 3, 5, 6]

Lists can be concatenated with ‘+’.

In [107]:
ListThing3 = [4,5,6,7]

In [108]:
myList1+ListThing3

Out[108]:
[1, 2, 9, 3, 5, 6, 4, 5, 6, 7]

Similarly, we can append one list to another without making another list

In [109]:
myList1.extend(ListThing3)

In [110]:
myList1

Out[110]:
[1, 2, 9, 3, 5, 6, 4, 5, 6, 7]

The idea of plus as concatenation is extended to multiplication:

In [118]:
[1,2]*3

Out[118]:
[1, 2, 1, 2, 1, 2]

This may be most useful for creating an empty data structure. For instance, here we make a list with 100 elements all initialized to zero.

In [121]:
Hundred_zeros = [0]*100


We can delete items from a list a few ways. Pop( ) will delete an item and return the value. The del keyword will delete any item or range of items its given without returning a value.

In [111]:
myList1.pop(3) #remove from position 3. To remove from the right end, do pop() with no argument

Out[111]:
3
In [112]:
myList1

Out[112]:
[1, 2, 9, 5, 6, 4, 5, 6, 7]

Between append( ) and pop( ), we can use lists as stacks. If we use pop(0) with append( ), we get a queue. We can also seek out list items with a particular value and remove them.

In [113]:
myList1.remove(9) #seek out the first occurrence of 9 from the left and remove it.

In [114]:
myList1

Out[114]:
[1, 2, 5, 6, 4, 5, 6, 7]

There are also several built-in functions for basic manipulation, including sort( ), count( ), reverse( ), and index( ) which returns the index of the first occurrence of something found in the list.

### Flow Control with Lists¶

One of the most powerful things to do with a list is looping over them with a for loop. Unlike older languages that need a counting variable, we can iteratively access each element with the “in” keyword and store that in a local variable (i in the example below).

In [117]:
for i in myList1:
print(i)

1
2
5
6
4
5
6
7


We can even iterate through two or more lists at a time, as long as they’re the same length

In [123]:
pet_names = ["Fluffy", "Dino", "Spot", "Fido"]
pet_ages = [2,3,5,1]
for name, age in zip(pet_names,pet_ages):
print(name, age)

Fluffy 2
Dino 3
Spot 5
Fido 1


### List Comprehension¶

Another powerful feature is list comprehension. This lets us build lists from other lists by putting loops inside the list.

In [126]:
X = [1,2,3,4]
X2 = [a*a for a in X]
print(X2)

[1, 4, 9, 16]


This can be extended to multiple nested loops, and can even contain conditionals.

In [129]:
[(x, y, x + y) for x in [1,2,3,4] for y in [3,4,5] if x < y]

Out[129]:
[(1, 3, 4),
(1, 4, 5),
(1, 5, 6),
(2, 3, 5),
(2, 4, 6),
(2, 5, 7),
(3, 4, 7),
(3, 5, 8),
(4, 5, 9)]

The range function gives a quick way to make a list containing a sequence.

In [138]:
for a in range(5): #range(5) gives [0,1,2,3,4]
print(a)

0
1
2
3
4

In [139]:
for b in range(4,14,2): #start at 4, stop before you get to 14, and count by 2
print(b)

4
6
8
10
12


Back To Index