Lists and Tuples

Acknowledgement : the contents of this notebook are partially based on the book "Starting Out with Python (3rd Edition)".

A sequence is an object that holds multiple items of data, stored one after the other. The difference between lists and tupes is that list is mutable, whereas tuple is immutable.

In [1]:
# sequences
odd_numbers = [1,3,5,7,9,11]
print(odd_numbers)
print(type(odd_numbers))

[1, 3, 5, 7, 9, 11]
<class 'list'>

In [2]:
names = ['John','Marry','Tom','Taylor']
print(names)
print(type(names))

['John', 'Marry', 'Tom', 'Taylor']
<class 'list'>

In [3]:
info = ['Dominica', 27, 23000]
print(info)
print(type(info))

['Dominica', 27, 23000]
<class 'list'>


Lists

A list is an object that contains multiple data items. Lists are mutable, i.e., their contents can be changed during a program's execution. Items may be added to them or removed from them.

In [4]:
# list() function
numbers = list(range(5))
print(numbers)

[0, 1, 2, 3, 4]

In [5]:
# the repetition operator makes multiple copies of a list : list * n
numbers = [0]*5
print(numbers)

[0, 0, 0, 0, 0]

In [6]:
numbers = [1,2,3]*3
print(numbers)

[1, 2, 3, 1, 2, 3, 1, 2, 3]

In [7]:
# iterating over a list with the for loop
numbers = [3,5,7,9,11]
for n in numbers:
print(n)

3
5
7
9
11

In [8]:
# indexing : indexing in Python starts at 0

my_list = [10,20,30,40]

print(my_list[0],my_list[1],my_list[2],my_list[3])

10 20 30 40

In [9]:
# indexing : negative index
my_list = [10,20,30,40]
print(my_list[-1],my_list[-2],my_list[-3],my_list[-4])

40 30 20 10

In [10]:
print(my_list[4]) # index out of range

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-10-35925ee7e800> in <module>()
----> 1 print(my_list[4]) # index out of range

IndexError: list index out of range
In [11]:
# the len function returns the length of a sequence
my_list = [10,20,30,40]
size = len(my_list)

print(size)

4

In [12]:
my_list = [10,20,30,40]
index = 0
while index < len(my_list):
print(my_list[index])
index += 1

10
20
30
40

In [13]:
# lists are mutable : we can modify the elements of the list.

numbers = [1,2,3,4,5]
print(numbers)

numbers[0] = 99
print(numbers)

new_numbers = numbers

new_numbers[1] = 99
print(new_numbers)

print(numbers)

[1, 2, 3, 4, 5]
[99, 2, 3, 4, 5]
[99, 99, 3, 4, 5]
[99, 99, 3, 4, 5]

In [14]:
# create a list with 5 elements
numbers = [0]*5

# fill the list with the value 99
index = 0
while index < len(numbers):
numbers[index] = 99
index += 1

print(numbers)

[99, 99, 99, 99, 99]

In [15]:
# concatenating lists : you can use + operator (or augmented assignment +=) to concatenate the lists

list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = list1+list2

print(list3)

[1, 2, 3, 4, 5, 6, 7, 8]

In [16]:
list1 = ['one','two','three']
list2 = ['four','five','six']
list3 = list1 + list2

print(list3)

['one', 'two', 'three', 'four', 'five', 'six']

In [17]:
list1 = [1,2,3,4]
list2 = [5,6,7,8]
list1 += list2

print(list1)

[1, 2, 3, 4, 5, 6, 7, 8]


List Slicing

A slicing expression selects a range of elements from a sequence.

In [18]:
# list_name[start : end]

days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
mid_days = days[2:5]

print(mid_days)

['Tuesday', 'Wednesday', 'Thursday']

In [19]:
# leave out the start index
numbers = [1,2,3,4,5]
print(numbers)
print(numbers[:3])

[1, 2, 3, 4, 5]
[1, 2, 3]

In [20]:
# leave out the end index
numbers = [1,2,3,4,5]
print(numbers)
print(numbers[2:])

[1, 2, 3, 4, 5]
[3, 4, 5]

In [21]:
# leave out both start and end index
numbers = [1,2,3,4,5]
print(numbers)
print(numbers[:])

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

In [22]:
# slicing with step value
numbers = [1,2,3,4,5,6,7,8,9,10]
print(numbers)
print(numbers[1:8:2])

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8]

In [23]:
# negative numbers as indexes
numbers = [1,2,3,4,5,6,7,8,9,10]
print(numbers)
print(numbers[-5:])

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[6, 7, 8, 9, 10]


Finding Items in Lists with the in Operator

You can search for an item in a list using the in operator.

In [1]:
# "item in list"? ... "item not in list"?

def main():
# create a list of students
student_names = ['Jakrawal','Nutnicha','Pornsakul','Eaksit']

# get a student name to search for
name = input("Enter a student's name : ")

# check if the student's name is in the list
if name in student_names:
print(name,'was found in the list.')
else:

# call the main function
main()

Enter a student's name : Eaksit
Eaksit was found in the list.


List Methods and Useful Build-in Functions

In [2]:
# the append method

def main():
# create an empty list
num_list = []

# get five numbers
for i in range(5):
# get a number from the user.
number = int(input('Enter a number : '))

# append the number to the list
num_list.append(number)

# display the numbers that were entered
for num in num_list:
print(num)

# call the main function
main()

Enter a number : 1
Enter a number : 2
Enter a number : 3
Enter a number : 4
Enter a number : 5
1
2
3
4
5

In [3]:
# the index method

def main():
# create a list
student_names = ['Jakrawal','Nutnicha','Pornsakul','Eaksit']

# display the list
print(student_names)

# get the name of student who dropped out
drop_student = input('Who dropped out? ')

try:
# get the index in the list
student_index = student_names.index(drop_student)

# get the name of new student
new_student = input('Who is the new student? ')

# replace the student who dropped out with the new student
student_names[student_index] = new_student

# display the list.
print(student_names)
except ValueError:

# call the main function
main()

['Jakrawal', 'Nutnicha', 'Pornsakul', 'Eaksit']
Who dropped out? Jakrawal
Who is the new student? Marut
['Marut', 'Nutnicha', 'Pornsakul', 'Eaksit']

In [4]:
# the insert method

def main():
# create a list
student_names = ['Jakrawal','Nutnicha','Pornsakul','Eaksit']

# display the list
print(student_names)

# insert a new student at element 0
student_names.insert(0,'Kanya')

print(student_names)

# call the main function
main()

['Jakrawal', 'Nutnicha', 'Pornsakul', 'Eaksit']
['Kanya', 'Jakrawal', 'Nutnicha', 'Pornsakul', 'Eaksit']

In [5]:
# the sort method
my_list = [9,1,0,2,8,6,7,4,5,3]
print('Original order : ', my_list)
my_list.sort()
print('Sorted order : ', my_list)

Original order :  [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]
Sorted order :  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [6]:
my_list = ['beta','alpha','delta','gamma']
print('Original order : ', my_list)
my_list.sort()
print('Sorted order : ', my_list)

Original order :  ['beta', 'alpha', 'delta', 'gamma']
Sorted order :  ['alpha', 'beta', 'delta', 'gamma']

In [8]:
# the remove method
def main():
# create a list
student_names = ['Jakrawal','Nutnicha','Pornsakul','Eaksit']

# display the list
print(student_names)

# get the name of student who dropped out
drop_student = input('Who dropped out? ')

try:
# remove the student's name from the list
student_names.remove(drop_student)

# display the list.
print(student_names)
except ValueError:

# call the main function
main()

['Jakrawal', 'Nutnicha', 'Pornsakul', 'Eaksit']
Who dropped out? Onkanya

In [9]:
# the reverse method

my_list = [1,2,3,4,5]
print('Original order : ', my_list)
my_list.reverse()
print('Reversed : ', my_list)

Original order :  [1, 2, 3, 4, 5]
Reversed :  [5, 4, 3, 2, 1]

In [10]:
# the del statement : e.g., del my_list[2]
my_list = [1,2,3,4,5]
print('Before deletion : ', my_list)

del my_list[2]

print('After deletion : ', my_list)

Before deletion :  [1, 2, 3, 4, 5]
After deletion :  [1, 2, 4, 5]

In [11]:
# the min and max functions
my_list = [5,4,3,2,50,40,30]
print('The lowest value is', min(my_list))
print('The highest value is', max(my_list))

The lowest value is 2
The highest value is 50


Copying Lists

To make a copy of a list, you must copy the list's element.

In [12]:
# reference the same list
list1 = [1,2,3,4]
list2 = list1
print(list1)
print(list2)

[1, 2, 3, 4]
[1, 2, 3, 4]

In [13]:
list1[0] = 99
print(list1)

[99, 2, 3, 4]

In [14]:
print(list2)

[99, 2, 3, 4]

In [15]:
# copy each element of the list

list1 = [1,2,3,4]
list2 = []

# copy the elements of list1 to list2
for item in list1:
list2.append(item)

print(list2)

[1, 2, 3, 4]

In [16]:
# another way to copy list
list1 = [1,2,3,4]
list2 = []+list1
print(list2)

[1, 2, 3, 4]


Processing Lists

In [24]:
# totaling the values in a list
def main():
# create a list
numbers = [2,4,6,8,10]

# create a variable to use as an accumulator
total = 0

# calculate the total of the list elements
for value in numbers:
total += value

# display the total of the list elements.
print('The total is',total)

# call the main function
main()

The total is 30

In [25]:
# averaging the values in a list
def main():
# create a list
numbers = [2,4,6,8,10]

# create a variable to use as an accumulator
total = 0

# calculate the total of the list elements
for value in numbers:
total += value

# calculate the average of the elements
average = total / len(numbers)

# display the total of the list elements.
print('The average is',average)

# call the main function
main()

The average is 6.0


Two-Dimensional Lists

A two-dimensional list is a list that has other lists as its elements.

In [17]:
# example
numbers = [['one','two'],['three','four'],['five','six']]
print(numbers)

[['one', 'two'], ['three', 'four'], ['five', 'six']]

In [18]:
print(numbers[0])

['one', 'two']

In [19]:
print(numbers[1])

['three', 'four']

In [20]:
print(numbers[2])

['five', 'six']

In [24]:
# assign random numbers to a two-dimensional list.
import random

def main():
# create a two-dimensional list.
values = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]

rows = len(values)
cols = len(values[0])

# fill the list with random numbers.
for r in range(rows):
for c in range(cols):
values[r][c] = random.randint(1,100)

# display the list.
print(values)

# call the main function
main()

[[35, 81, 80, 58], [5, 82, 58, 56], [10, 51, 82, 55]]


Extra : List Comprehension

In [ ]:
# numerical comprehension

In [26]:
my_list1 = [x**2 for x in range(10)]
print(my_list1)

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

In [27]:
my_list2 = [2**i for i in range(13)]
print(my_list2)

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]

In [28]:
my_list3 = [x for x in my_list1 if x % 2 == 0]
print(my_list3)

[0, 4, 16, 36, 64]

In [33]:
noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
#print(noprimes)

primes = [x for x in range(2, 50) if x not in noprimes]
print(primes)

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

In [ ]: