Lists
Python Programming
1 Cristan Josh S. Nuguid
Lesson objectives
1. Describe the characteristics of the
list data structure in Python
2. Perform basic operations with lists
including creation, concatenation,
repetition, slicing, and traversing
3. Use string methods that require lists
(join, split)
4. Use lists in functions
2 Python Programming
The list data structure
In Python, a list is a mutable
sequence of values
Each value in the list is an element
or item
Elements can be any Python data
type
Lists can mix data types
Elements can be nested lists
3 Python Programming
Creating lists
numbers = [1, 2, 3, 4]
print numbers
cheeses = ['swiss', 'cheddar',
'ricotta', 'gouda']
print cheeses
4 Python Programming
Creating lists
mixed = [1, 'a', 3.45]
print mixed
single = ['z']
print single, type(single)
empty = []
print empty
5 Python Programming
Repeating a list
Use the * operator:
meat = ['spam']*4
print meat
print [1, 2, 3]*3
6 Python Programming
List indexing
Elements within a list are indexed
(see Lesson 10)
print cheeses[0]
Lists are mutable
cheeses[0] = 'Feta'
print cheeses
7 Python Programming
Slicing a list
Like strings and other sequences,
lists can be sliced
print cheeses[1:4]
print cheeses[:2]
print cheeses[2:]
8 Python Programming
Changing a slice
roster = ['Meghan', 'Tricia', 'Juan',
'Alton', 'Darrel', 'Jen']
print roster
roster[1:3] = ['Sam', 'Kerri']
print roster
roster[3:5] = ['Tayla']
print roster
9 Python Programming
Inserting elements
Slice notation
roster[2:2] = ['Dana', 'Ryan']
print roster
10 Python Programming
Deleting elements
Set slice to empty list
roster[3:5] = []
print roster
The del keyword
del roster[2:3]
print roster
11 Python Programming
The insert and append methods
The insert method
[Link](2,'Jakob')
print roster
The append method
[Link]('Tonya')
print roster
12 Python Programming
The extend method
Adds a list to the end of an
existing list
adds = ['Ian', 'Stacie']
[Link](adds)
print roster
13 Python Programming
Extending a list
Can also use += operator
roster += ['Anya']
print roster
14 Python Programming
Using the + operator
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print a, b, c
*The + operator returns a new list that
is a concatenation of two lists
15 Python Programming
Note on list operations
Be careful when using the +
operator and append method
Try this:
d = c + 7
Or this
[Link](b)
print c
16 Python Programming
List assignment and aliasing
a = [1, 2, 3, 4]
b = a
c = a[:]
a[2] = 9
print a, b, c
*The slice operator returns a copy of a list
17 Python Programming
Other list methods
[Link]()
print roster
[Link]()
print roster
18 Python Programming
Other list methods
print [Link]('Tonya')
print [Link]('Tonya', 2, 5)
print [Link]('Sam')
[Link]('Sam')
print roster
19 Python Programming
The join string method
Concatenates a sequence of
strings into a single string with
sep inserted between each item.
Syntax: [Link](list)
20 Python Programming
The split string method
Returns a list of words from a
string using sep as the delimiter
string
Syntax: [Link](list)
21 Python Programming
Example: join_split.py
t = ['pining', 'for', 'the', 'fjords']
delimiter = '_'
s = [Link](t)
print s
u = [Link](delimiter)
print u
22 Python Programming
Example
print ''.join(t)
print ' '.join(t)
print '\t'.join(t)
23 Python Programming
Traversing a list
for index in range(len(roster)):
print roster[index]
for student in roster:
print student
for index, student in enumerate(roster):
print index, student
24 Python Programming
Traversing a list
What does this do?
empty = []
for x in empty:
print x
25 Python Programming
Nested lists
nested = [[1,2,3],[4,5,6],[7,8,9]]
print nested
print nested[0]
print nested[0][1]
26 Python Programming
Traversing nested lists
for i in range(len(nested)):
for j in range(len(nested[i])):
print nested[i][j]
27 Python Programming
Traversing nested lists
for nest in nested:
for item in nest:
print item
28 Python Programming
Using lists: [Link]
def cumulate(seq):
c_sum = 0
for item in seq:
c_sum += item
return c_sum
a = [12, 78, 32, 82]
s = cumulate(a)
print s
29 Python Programming
Returning lists from functions:
only_upper.py
def only_upper(t):
res = []
for s in t:
if [Link]():
[Link](s)
return res
text = 'Bold cOlOrs Make for Easy Reading'
secret = only_upper(text)
print secret
30 Python Programming
Modifying lists in functions
In Python, arguments are passed
by reference
The parameter in the function is an
alias for the argument that was
passed in
If a mutable object is changed inside
the function, it is also changed
outside the function
31 Python Programming
Example: [Link]
def change(seq):
print 'Passed in: ' + str(seq)
[Link]('new item')
print 'Changed to: ' + str(seq)
original = [1, 2, 3]
print original
change(original)
print original
32 Python Programming
Example: [Link]
def change(seq):
print 'Passed in: ' + str(seq)
[Link]('new item')
print 'Changed to: ' + str(seq)
new_seq = ['created','in','function']
print 'New seq: ' + str(new_seq)
original = [1, 2, 3]
new_seq = ['outside','the','function']
print original
change(original)
print original
print new_seq
33 Python Programming
Suggested exercises
Exercise 10.5 – Solving the
"Birthday Paradox" by a Monte
Carlo simulation
Exercise 10.6 – Removing
duplicates from a list
Exercise 10.8 – Bisection search
34 Python Programming