A Python list
object is a sequential (ordered) collection of Python data values (objects)
A list is denoted by [ element1, element2, ... , elementn ]
, where consecutive objects of the list are separated by a comma.
List elements can be of any data type (str
, int
, float
, bolean
, list
, …)
An empty list is created by
a_list = []
List elements may be of different types, for example
a_list = ['b', 17, 3.14, True, ['dog', 13]]
The previous example is one of a nested list because the fifth element of the list is a list. The fifth element, because it is a list, is referred to as a sub-list of a_list
len()
FunctionThe following code snippet results in “5” being printed.
a_list = ['b', 17, 3.14, True, ['dog', 13]]
n = len(a_list)
print(n)
NOTE: The sub-list is counted as a single element.
Syntax for accessing list elements is the same as that for strings, and the index operator starts with the value 0 for element 1.
a_list = ['b', 17, 3.14, True, ['dog', 13]]
print(a_list[1]) # print result: 17
print(a_list[4][0]) # print result: dog
print(a_list[4 - 2]) # print result: 3.14
print(a_list[-1]) # print result: ['dog', 13]
in
and not in
OperatorsThese are boolean operators, so the result will be either True
or False
a_list = ['b', 17, 3.14, True, ['dog', 13]]
print(17 in a_list) # print result: True
print(18 not in a_list) # print result: True
print('cat' in a_list[4]) # print result: False
The +
operator concatenates lists (adds lists or adds to a list)
a_list = [3, 2, 1]
b_list = [1, 2, 3]
print(a_list + b_list) # print result: [3, 2, 1, 1, 2, 3]
print(a_list + [b_list]) # print result: [3, 2, 1, [1, 2, 3]]
Activity 1: Write program with a function that creates a list of \(x\) and \(y\) coordinate pairs, each pair is a sub-list of the list being created. The function parameters are range limits on the random selection process of \(x\) and \(y\) coordinates, and the number of sub-lists (pairs) of \(x - y\) coordinates to be generated. Begin with an empty list. Use the concatenation operator +
to add new pairs to the list. Then, include a function that takes the list and prints out the \(x\) and \(y\) coordinate pairs, one line at a time.
def xy_list(n, xmin, xmax, ymin, ymax):
def print_xy(list_in):
The *
repeats the items in a list a given number of times.
a_list = [3, 2, 1]
print(a_list * 2) # print result: [3, 2, 1, 3, 2, 1]
print([a_list] * 2) # print result: [[3, 2, 1], [3, 2, 1]
Activity 2: Write a function that randomly selects integers from a given range [r_min, r_max] for n iterations and keeps track of how many times a given integer from the range is selected. Use the *
operator to create a list of length l, where l is determined using the parameter values r_min and r_max, filled with a zero for each element. The function prints how many times each number is chosen in the process.
def how_frequent(r_min, r_max, n):
Activity 3: Write a turtle graphics program that plots points at the locations generated and stored in Activity 1.
:
The slice operator for lists is similar to the string slice operator.
a_list = [5, 4, 3, 2, 1]
print(a_list[2:4]) # result: [3, 2]
print(a_list[:3]) # result: [5, 4, 3]
print(a_list[3:]) # result: [2, 1]
print(a_list[:]) # result: [5, 4, 3, 2, 1]
Lists are mutable (elements of a list can be changed)
a_list = [5, 4, 3, 2, 1]
a_list[1] = 0
print(a_list) # result: [5, 0, 3, 2, 1]
del
Elements of a list may be deleted (this is unlike strings, where a new string must be created that does not include the deleted characters)
a_list = [5, 4, 3, 2, 1]
del a_list[1]
print(a_list) # result: [5, 3, 2, 1]
b_list = ['a', 'b', 'c', 'd', 'e']
del b_list[0:2]
print(b_list) # result: ['c', 'd', 'e']
Activity 4: Write a program that includes a function called replace(l_int)
, where l_int is an input list of integers from the interval [1, 5] of any finite length. The function traverses the list and replaces every occurrence of integer 1 with ‘one’, integer 2 with ‘two’ and so on up to and including the integer 5. The edited list is returned to the main program where it is printed. Include a function gen_list(n)
that generates the list of n entries that is passed onto replace(l_int)
.
Recall, an object is anything a variable can reference.
a = 7
b = 'dog'
c = [1, 2, 3]
An object may have a unique reference, or more than one reference
a = 7
b = 7
print(b is a) # result: True
a = 'cat'
b = 'cat'
print(b is a) # result: True
Now, consider
a = [1, 2, 3]
b = [1, 2, 3]
print( b is a) # result: False
print( b == a) # result: True
The difference between the list case and the int
and str
cases is that Python creates two lists, one referenced by a
and another by b
. The lists are equal (they have the same length, and each element is the same.)
Try the following in a scratch code window or PythonTutor:
a = [1, 2, 3]
b = a
print(b is a)
b[0] = -1
print(b is a)
print(b)
print(a)
The case above is an example of aliasing. The variable name b
is an alias of the list object [1, 2, 3]
. Its original name, or other name, is a
.
The variables a
and b
are references to the same object. Using either reference to modify, or mutate, the object does not change the fact that both names refer to the same object. Consequently a is b
and b is a
before and after the mutation of the object.
In the examples above, Python automatically points a
and b
to the same str
and int
object because they are immutable, whereas the list
object is mutable.
Activity 5: (a) Write a function called interlace(l1, l2)
that accepts two lists of equal length as inputs. The function returns a new list generated by interlacing the two lists. That is, the new_list = [l1_0, l2_0, l1_1, l2_1, …, l1_n, l2_n], where l1_i is the ith indexed element of l1 and l2_i is the ith indexed element of l2. Write a function that generates a list of n letters, selected randomly, as a way to provide the interlace(l1,l2)
function with different types of lists. (b) Modify the function so that it accepts lists of unequal lengths. The new list will have interlaced terms at the front, and the end will be made up of the remaining terms of the longer list. (c) Next, implement a scheme for unequal length lists such that the number of consecutive terms in the new list that come from the longest list is minimized.
Aliasing a list may be useful in some instances and confusing in others.
How can a programmer mutate a list, but keep the original list in its original state? By cloning the original.
a = [1, 2, 3]
b = a[:]
b[0] = -1
print(a)
print(b)
List objects have numerous useful methods for accessing list information or mutating a given list. Refer to the text book for a short list of commonly used methods. Methods can be categorized by the result. Some mutate the list (such as appending an element or sorting the list), others return information (such as the index of the position of a value’s first occurrence), and some are hybrid methods that both mutate and return (such as the pop method that returns the element at a specified location and removes it from the list)
Activity 6: Write a function called two_or_more(n)
, where the parameter n is the number of times random integers from the range [1,365] are selected and added to a list. The list is then searched to determine if any number in the list appears more than once. The function returns True if so, and False otherwise. HINT: Consider using the append()
and count()
methods for lists.
Activity 7: The Birthday Problem is a classic probability application that yields some surprising results. A typical phrasing of the problem is “what is the smallest group of people (number of people = n) required so that the probability of at least two people having the same birthday is at least 0.5?” Use the function two_or_more(n)
created in the previous activity to devise a scheme to determine the answer to this question using an experimental (programming) method. Now, use you code to experimentally determine the minimum group size n required so that the probability of at least three people having the same birthday is greater than or equal to 0.50.
Activity 8: Use PyCharm and turtle graphics to replicate the figure shown on the Wikipedia page on the birthday problem. The Birthday Problem
The append()
and pop()
list methods are useful when drawing node-rewriting L-systems. The “[" character invokes an append(location, heading)
method, and the “]” character in the instruction string invokes the pop()
method.
Activity 9: Use PyCharm and turtle graphics to draw one of the figures shown here. The code below was used in a previous activity in Chapter 9. Next, add color to the figure. Then, use the random
module to incorporate randomness in the drawing process. That is, write code that results in random, variable lengths, angles and color.
import turtle
def apply_rules(ch):
if ch == 'X':
newstr = 'F[-X][X]F[-X]+FX' # Rule 1
elif ch == 'F':
newstr = 'FF' # Rule 2
else:
newstr = ch # ch is a constant
return newstr
def process_string(old_str):
newstr = ""
for ch in old_str:
newstr = newstr + apply_rules(ch)
return newstr
def create_L_system(num_iters, axiom):
start_string = axiom
end_string = ""
for i in range(num_iters):
end_string = process_string(start_string)
start_string = end_string
return end_string
def draw_L_system(t, instructions, angle, distance):
def main():
length = 20
scale_factor = 1.0
angle = 25
axiom = 'X'
iterations = 3
inst = create_L_system(iterations, axiom)
# print(inst)
t = turtle.Turtle()
wn = turtle.Screen()
wn.tracer(10, 1)
t.hideturtle()
t.up()
t.goto(-250, -250)
t.left(60)
t.down()
draw_L_system(t, inst, angle, scale_factor*length)
wn.exitonclick()
main()
Fill in the function draw_L_system
using the following turtle plotting directives:
‘F’ : foward(distance)
‘+’ : right(angle)
‘-’ : left(angle)
‘[’ : push position and angle (use the list append() method)
‘]’ : pop position and angle (use the list pop() method)
Items can be added to a list using either the concatenation operator +
or the append()
method.
l = [1, 2, 3]
l = l + ["dog"]
print(l)
item = l.pop()
l.append(item)
print(l)
A list may be traversed using the range()
and len()
functions
l = ['a', 'b', 'c']
for i in range(len(l)):
print(l[i])
Or, a list may be traversed by iteration by item
l = ['a', 'b', 'c']
for item in l:
print(item)
Example:
def switch_a_roo(l_in):
for i in range(len(l_in)-1):
l_in[i], l_in[i+1] = l_in[i+1], l_in[i]
a_list = [1, 'a', 2, 'b', 3, 'c']
switch_a_roo(a_list)
print(a_list)
Modify the code so that pairs are switched.
Modify the code so that the original list is kept in its initial state.
A Pure Function is one that:
communicates with its calling function by parameter(s) and return value only.
does not modify the parameter(s).
always returns the same result if the same parameters are passed to it.
does not depend on any state, or data, change during the program’s execution.
Example: make the following function switch_a_roo()
a pure function.
def switch_a_roo():
for i in range(0,len(a_list)-1, 2):
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
a_list = [1, 'a', 2, 'b', 3, 'c']
switch_a_roo()
print(a_list)
Some programming langues only allow the use of pure functions.
Programs using only pure functions are less error-prone, but may be less efficient.
Concise ways to create a list.
[<expression> for <item> in <sequence> if <condition>]
Examples
l = [i for i in range(0,11)]
l = [i for i in range(0,11) if i % 3 == 0 ]
a = [1, 2, 3]
b = [i*2 for i in a]
s = "0-9654-8534-X"
s_list = [ch for ch in s]
print(s_list)
s_list = [ch for ch in s if ch!='-']
print(s_list)
l_list = [int(ch) if ch!='X' else 10 for ch in s_list]
print(l_list)
Nest lists: lists within lists.
L-System is an example of an application. See Activity 9.
The split()
method for strings results in a list of words, or perhaps a single word.
sentence = 'Decorah is a city in Iowa'
words = sentence.split()
print(words)
print(sentence.split('c'))
print(sentence.split('q'))
The string method join()
reverses the split()
.
word_l = ['Where', 'is', 'Waldo?']
glue = " "
sentence = glue.join(word_l)
print(sentence)
Activity 10: Write a function that takes a sentence as an input and returns a sentence with the words in reverse order. Don’t for get to properly adjust the case on the words. Modify the function so that it reverses the character order of each word as well as the order of the words.
Activity 11: Write a function called mad_lib(n_l, o_l)
that generates a sentence with the format “The (noun) threw the (object1) at the (object2),” where the variable noun is randomly selected from the list of nouns n_l
, object1 is randomly selected from the list of objects o_l
, and object2 is randomly selected from the list n_l
, with object2 \(\ne\) noun. Use n_l = [‘dog’, ‘woman’, ‘man’, ‘cat’, ‘police officer’, ‘teacher’] and o_l = [‘ball’, ‘stick’, ‘kitchen sink’, ‘knife’, ‘pie’]
list
Type Conversion FunctionThe list(object)
function tries to covert in sequential object, such as a str
or a tuple
, into a list.
print(list("Decorah"))
A Tuple is a Python object that:
is a collection of related data
is sequential
is immutable
Example
smith_data = ('Twins', '2015', 'center field', 0.213, 53)
new_record = smith_data[:-1] + (54,)
Efficient way to assign variable names to items of a tuple.
(team, year, position, batting_average, hr_number) = smith_data
print(position, hr_number)
Switching order:
a = 1
b = 'dog'
(a,b) = (b, a)
print(a,b)
Example
def surface_area(radius):
sa = 4 * 3.14159 * radius**2
return (radius, sa)
print(surface_area(3))