Python Exam 2
concatenation(+) operator
+ operator creates NEW lists from the elements of the operand lists if you concatenate a list with 2 items and a list with 4 items, you will get a new list with 6 items (not a list with two sublists)
my_list = [5, 6, 18, -21] lastitem = my_list.pop() print(lastitem) print(my_list)
-21 [5, 6, 18]
numbers = list(range(10)) for index in range(len(numbers)): print(numbers[index], end = " ")
0 1 2 3 4 5 6 7 8 9
def multiplication(num, multiplier): if multiplier == 1: return num else: return num + multiplication(num, multiplier-1) print(multiplication(3, 4))
12
def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) factorial(5)
120
numbers = [0, 1, 2, 3, 4, 5, 6, 7] print(numbers[2], numbers[3]) print(numbers[-1], numbers[0]) print(numbers[len(numbers) - 1])
2 3 7 0 7
alist = ["hello", 2.0, 5, [10, 20]] print(len(alist))
4
print(len(['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]))
4
alist = [3, 67, "cat", 3.14, False] print(len(alist))
5
def sum_list_recursion(num_list): if len(num_list) == 1: return num_list[0] else: return num_list[0] + sum_list_recursion(num_list[1:]) num_list = list(range(101)) print(sum_list_recursion(num_list))
5050
def sum_recursion(n): if n == 1: return 1 else: return n + sum_recursion(n-1) sum_recursion(100)
5050
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(len(alist))
7
slicing (:)
A slice of a list is a sublist specified with colon notation. It is analogous to a slice of a string. A slicing expression, [a : b], selects a range of elements from a sequence. The first index is the starting point for the slice and the second number is one index past the end of the slice (up to but not including that element). If you omit the first index (before the colon), the slice starts at the beginning of the sequence. If you omit the second index, the slice goes to the end of the sequence
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(alist[2].upper())
CAT
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(57 in alist)
False
Aliasing (=)
If the variable var1 has a mutable value (such as a list), then a statement of the form var2 = var1 results in var2 referencing the same object as var1. Therefore, any change to the value of var2 affects the value of var1. Since variables refer to objects, if we assign one variable to another, both variables refer to the same object. Because the same list has two different names, a and b, we say that it is aliased. Changes made with one alias affect the other.
Do the elements of the list have to be the same type?
No
def Fibonacci(n): if n == 1: return 1 elif n == 2: return 1 else: return Fibonacci(n-1) + Fibonacci(n-2) for i in range(1, 6): print("The {:2d}th Fib number is {:2d}".format(i, Fibonacci(i)))
The 1th Fib number is 1 The 2th Fib number is 1 The 3th Fib number is 2 The 4th Fib number is 3 The 5th Fib number is 5
sort method
The sort method can be used to sort a list in ascending, descending or user defined order.list_name.sort() will sort the given list in ascending order.list_name.sort(reverse=True) will sort the given list in descending order.list_name.sort(key=..., reverse=...) will sort according to user's choice
T or F. Lists are mutable
True
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(3.14 in alist)
True
fruit = ["apple", "orange", "banana", "cherry"] print("apple" in fruit) print("pear" in fruit) print("pear" not in fruit)
True False True
a = [81, 82, 83] b = a print(a == b) print(a is b)
True True
T or F: List cannot be used as keys for dictionary
True because keys are immutable and unique (no duplicate) but multiple keys can have the same value
What does it mean that lists are mutable
Unlike strings, lists are mutable. This means we can change an item in a list by accessing it directly as part of the assignment statement. Using the indexing operator on the left side of an assignment, we can update one of the list items.
remove
We can use the remove(item) method to remove an element
repetition (*)
When the operand on the left side of the * symbol is a sequence (such as a list) and the operand on the right side is an integer, it becomes the repetition operator. The repetition operator makes multiple copies of a list and joins them all together.
What holds the elements of the list?
[ ] - square brackets
fruit = ["apple", "orange", "banana", "cherry"] mixed_list = fruit + [6, 7, 8, 9] print(mixed_list)
["apple", "orange", "banana", "cherry", 6, 7, 8, 9 ]
text = "word1anotherword23nextone456lastone333" number_string_list = [x for x in text if x.isdigit()] print(number_string_list)
['1', '2', '3', '4', '5', '6', '3', '3', '3']
pyString = '12345' print(sorted(pyString, reverse = True))
['5', '4', '3', '2', '1']
mixed = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] print(mixed[2]) print(mixed[2][0]) print(mixed[3][1])
['Brie', 'Roquefort', 'Pol le Veq'] Brie 2
s_list = list("Horned Frog") print(s_list)
['H', 'o', 'r', 'n', 'e', 'd', ' ', 'F', 'r', 'o', 'g']
full_name = "John Adam Doe" name_list = full_name.split(" ") print(name_list)
['John', 'Adam', 'Doe']
colors = ['red', 'orange', 'yellow', 'green', 'blue'] colors2 = [item.upper() for item in colors] print(colors2)
['RED', 'ORANGE', 'YELLOW', 'GREEN', 'BLUE']
a_sentence = "This is a wonderful world!" word_list = a_sentence.split(" ") print(word_list) word_list = a_sentence.strip("!").split(" ") print(word_list)
['This', 'is', 'a', 'wonderful', 'world!'] ['This', 'is', 'a', 'wonderful', 'world']
sorted("This is a test string from Ana".split(), key = str.lower)
['a', 'Ana', 'from', 'is', 'string', 'test', 'This']
alist = ["a", "d", "f"] alist[1:1] = ["b", "c"] print(alist) alist[4:4] = ["e"] print(alist)
['a', 'b', 'c', 'd', 'f'] ['a', 'b', 'c', 'd', 'e', 'f']
alist = ["a", "b", "c", "d", "e", "f"] alist[1:3] = [] print(alist)
['a', 'd', 'e', 'f']
pyList = ['e', 'a', 'u', 'o', 'i'] print(sorted(pyList))
['a', 'e', 'i', 'o', 'u']
pyTuple = ('e', 'a', 'u', 'o', 'i') print(sorted(pyTuple))
['a', 'e', 'i', 'o', 'u']
alist = ['a', 'b', 'c', 'd', 'e', 'f'] del alist[1:5] print(alist)
['a', 'f']
alist = ["a", "b", "c", "d", "e", "f"] alist[1:3] = ["x", "y"] print(alist)
['a', 'x', 'y', 'd', 'e', 'f']
a_list = ['a', 'b', 'c', 'd', 'e', 'f'] print(a_list[1:3]) print(a_list[:4]) print(a_list[3:]) print(a_list[:]) print(a_list[-2:]) print(a_list[:-2])
['b', 'c'] ['a', 'b', 'c', 'd'] ['d', 'e', 'f'] ['a', 'b', 'c', 'd', 'e', 'f'] ['e', 'f'] ['a', 'b', 'c', 'd']
s_list = ["cccc", "b", "dd", "aaa"] print(sorted(s_list, key = len)) print(sorted(s_list, key = str.lower))
['b', 'dd', 'aaa', 'cccc'] ['aaa', 'b', 'cccc', 'dd']
a = ['one', 'two', 'three'] del a[1] print(a)
['one', 'three']
fruit = ["banana", "apple", "cherry"] fruit[0] = "pear" fruit[-1] = "orange" print(fruit)
['pear', 'apple', 'orange']
numbers = [0] * 5 print(numbers) numbers = [1, 2, 3] * 2 print(numbers) print(numbers * 3) print(numbers[2] * 3 )
[0, 0, 0 ,0 ,0] [1, 2, 3, 1, 2, 3] [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] 9
counter_list = [0] * 10 print(counter_list)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
print([0] * 4) print([1, 2, ["hello", "goodbye"]] * 2)
[0, 0, 0, 0] [1, 2, ['hello', 'goodbye'], 1, 2, ['hello', 'goodbye']
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] numbers.insert(10, -1) print(numbers) numbers.insert(0, -2) print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1] [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1]
my_list = [] for i in range(10): my_list += [i] print(my_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers = [] for i in range(10): numbers.append(i) print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers = list(range(10)) print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares = [] for x in range(10): squares.append(x**2) print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares2 = [x**2 for x in range(10)] print(squares2)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
even_numbers = [] for i in range(10): if i % 2 == 0: even_numbers.append(i) print(even_numbers)
[0, 2, 4, 6, 8]
even_numbers = list(range(0, 10, 2)) print(even_numbers) odd_numbers = list(range(1, 10, 2)) print(odd_numbers)
[0, 2, 4, 6, 8] [1, 3, 5, 7, 9]
text = "word1anotherword23nextone456lastone333" numbers = [int(x) for x in text if x.isdigit()] print(numbers)
[1, 2, 3, 4, 5, 6, 3, 3, 3]
nums = [1, 2] print(nums + [3, 4])
[1, 2, 3, 4]
my_list = [3, 45, 1, 23] print(sorted(my_list)) print(my_list) # the original list remains the same print('') my_list.sort() # change the original list print(my_list)
[1, 3, 23, 45] [3, 45, 1, 23,] [1, 3, 23, 45]
numbers = list(range(1, 11)) odd_numbers = [ x for x in numbers if x % 2 != 0] print(odd_numbers)
[1, 3, 5, 7, 9]
list3 = [item for item in range(1, 21) if item % 2 == 0 and item % 5 == 0] print(list3)
[10, 20]
numbers = [17, 23] vocabulary = ["iteration", "selection", "control"] numbers.extend(vocabulary) print(numbers)
[17, 23, 'iteration', 'selection', 'control']
what is the output of the following: numbers = [17, 23] vocabulary = ["iteration", "selection", "control"] new_list = numbers + vocabulary print(new_list)
[17, 23, 'iteration', 'selection', 'control']
numbers = list(range(1, 11)) even_numbers = [ x for x in numbers if x % 2 == 0] print(even_numbers)
[2, 4, 6, 8, 10]
list2 = [item+1 for item in range(1, 6, 2)] print(list2)
[2, 4, 6]
my_list = [3, 45, 1, 23] my_list.reverse() print(my_list)
[23, 1, 45, 3]
my_list = [3, 6, 9, 10, 11] my_list.insert(1, 12) print(my_list)
[3, 12, 6, 9, 10, 11]
alist = [1, 2, 3, 4] alist[0], alist[3] = alist[3], alist[0] print(alist)
[4, 2, 3, 1]
alist = [1, 2, 3, 4] temp = alist[0] alist[0] = alist[3] alist[3] = temp print(alist)
[4, 2, 3, 1]
alist = [4, 2, 8, 6, 5] blist = alist blist[3] = 999 print(alist) print(blist)
[4, 2, 8, 999, 5] [4, 2, 8, 999, 5]
my_list = [45, 32, 88] numbers = [4, 23] print(my_list) print(sorted(my_list)) numbers = (4, 21) my_list.extend(numbers) print(my_list) print(sorted(my_list))
[45, 32, 88, 4, 23] [4, 23, 32, 45, 88] [45, 32, 88, 4, 21] [4, 21, 32, 45, 88]
my_list = [45, 32, 88] numbers = [4, 23] my_list.insert(1, numbers) print(my_list) my_list.append(numbers) print(my_list) my_list.extend(numbers) print(my_list) my_list += numbers print(my_list)
[45, [4, 23], 45, 32, 88] [45, [4, 23], 45, 32, 88, [4, 23]] [45, [4, 23], 45, 32, 88, 4, 23, [4, 23], 4, 23] [45, [4, 23], 45, 32, 88, 4, 23, [4, 23], 4, 23, 4, 23]
my_list = [] my_list.append(5) my_list.append(27) my_list.append(3) my_list.append(12) print(my_list)
[5, 27, 3, 12]
numbers = [5, 6, 18, -21] numbers.remove(5) print(numbers) numbers.remove(18) print(numbers)
[6, 18, -21] [6, -21]
b_list = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(b_list[4:])
[[ ], 3.14, False]
numbers = [17, 23] vocabulary = ["iteration", "selection", "control"] nested_list = [ numbers, vocabulary ] print(nested_list)
[[17, 23], ['iteration', selection', 'control']]
alist[:] = [] print(alist)
[]
extend()
adds all the elements of an iterable (list, tuple, string etc.) to the end of the list.
fruits = ["apple", "orange", "banana", "cherry"] for a_fruit in fruits: print(a_fruit, " ", end="")
apple orange banana cherry
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(alist[2][0]) print(alist[3][0])
c 56
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(alist[2]) print(alist[5])
cat 3.14
Lists are separated by
commas ,
import random my_randoms = random.sample(range(1, 101), 20)
generates 20 random numbers from 1-100
membership (in)
in and not in are boolean operators that test membership in a sequence.
alist = [] for i in range(3): e = int(input("Please input an integer: ")) alist.append(e) print("The min is {} and the max is {}".format(max(alist), min(alist)))
input 3 numbers and outputs the max and min
insert() method
inserts an element to the list at the specified index e.g. list.insert(index, number)
join
inverse of the split method
wd_list = ["red", "blue", "green"] glue = ';' s = glue.join(wd_list) print(s) print(wd_list)
red;blue;green ['red', 'blue', 'green']
del statement
removes an element from a list by using its position
pop()
removes the item at the given index from the list and returns the removed item
numbers = [17, 123, 87, 34, 66, 8398, 44] search = int(input("Which number are you looking for? ")) if search in numbers: print("Found it. Number {} is at {}th postion".format(search, numbers.index(search))) else: print(search, "is not in the list")
returns the index of the specified element
count() method
returns the number of times the specified element appears in the list
dictionary
sequence collection that stores key-value pairs that map immutable keys to values, just as a conventional dictionary maps words to definitions. The association, or mapping, is from a key, which can be any immutable type (e.g., string, tuple, numbers), to a value, which can be any Python data object. Dictionaries are mutable. Dictionaries do not support indexing, and thus, do not support slicing.
difference between sort and sorted()
sorted() doesn't modify original sequence .sort modifies original list
sorted() function
sorts any sequence (list, tuple, string) and always returns a list with the elements in sorted manner, WITHOUT modifying the original sequence syntax: sorted(iterable, key, reverse) the last two are optional
It is a list within another list
sublist
difference between append and concatenation
with append the original list is simply modified; with concatenation an entirely new list is created
my_dict = {} my_dict["Success"] = "Hard work" my_dict["Data Science"] = "Python" print(my_dict)
{'Success': 'Hard work', 'Data Science': 'Python'}