Feng Li
School of Statistics and Mathematics
Central University of Finance and Economics
The conditions used in while and if statements can contain any operators, not just comparisons.
The comparison operators in and not in check whether a value occurs (does not occur) in a sequence. The operators is and is not compare whether two objects are really the same object; this only matters for mutable objects like lists. All comparison operators have the same priority, which is lower than that of all numerical operators.
Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c.
Comparisons may be combined using the Boolean operators, and and or, and the outcome of a comparison (or of any other Boolean expression) may be negated with not. These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to ((A and (not B)) or C). As always, parentheses can be used to express the desired composition.
The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.
Keyword (Scalar) | Function | Bitwise | True if . . .
-----------------------------------------------------------------
and | logical_and() | & | Both True
or | logical_or() | | | Either or Both True
not | logical_not() | ~ | Not True
| logical_xor() | ^ | One True and One False
The core logical operators are
All comparisons are done element-by-element and return either True or False. Note that in Python, unlike C, assignment cannot occur inside expressions. it avoids a common class of problems encountered in C programs: typing =
in an expression when ==
was intended.
The functions all()
and any()
take logical input and are self-descriptive. all returns True if all logical elements in an array are 1. If all is called without any additional arguments on an array, it returns True if all
elements of the array are logical true and 0 otherwise. any returns logical(True) if any element of an array
is True .
A number of special purpose logical tests are provided to determine if an array has special characteristics. Some operate element-by-element and produce an array of the same dimension as the input while other produce only scalars. These functions all begin with is .
isnan
isinf
isfinite
isposfin
isnegfin
iscomplex
isreal
is_string_like
is_numlike
isscalar
isvector
The list data type has some more methods. Here are all of the methods of list objects in Python 3:
list.append(x)
: Add an item to the end of the list. Equivalent to a[len(a):] = [x].a = [1, 2, 4, 5,8, 100 ,1005]
a.append(2)
a
[1, 2, 4, 5, 8, 100, 1005, 2]
list.extend(L)
: Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.b = ["Feng", "Li", "Love"]
a.extend(b)
a
[1, 2, 4, 5, 8, 100, 1005, 2, 'Feng', 'Li', 'Love']
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).a.insert(1,"Hello")
a
[1, 'Hello', 2, 4, 5, 8, 100, 1005, 2, 'Feng', 'Li', 'Love']
list.remove(x)
: Remove the first item from the list whose value is x. It is an error if there is no such item.a.remove("Hello")
a
[1, 4, 5, 8, 100, 1005, 2, 'Feng', 'Li']
list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)a.pop(2)
a
[1, 'Hello', 4, 5, 8, 100, 1005, 2, 'Feng', 'Li', 'Love']
a.pop()
a
[1, 'Hello', 4, 5, 8, 100, 1005, 2, 'Feng', 'Li']
list.clear()
: Remove all items from the list. Equivalent to del a[:]
.list.index(x)
: Return the index in the list of the first item whose value is x. It is an error if there is no such item.a.index("Love")
9
list.count(x)
: Return the number of times x appears in the list.a.count("Love")
1
list.sort()
: Sort the items of the list in place.b = [1,7,2,14]
b.sort()
b
[1, 2, 7, 14]
list.reverse()
: Reverse the elements of the list in place.a.reverse()
a
['Love', 'Li', 'Feng', 2, 1005, 100, 8, 5, 4, 1]
list.copy()
: Return a shallow copy of the list. Equivalent to a[:].b = a.copy()
b
['Love', 'Li', 'Feng', 2, 1005, 100, 8, 5, 4, 1]
The del statement
There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop()
method which returns a value. The del
statement can also be used to remove slices from a list or clear the entire list
a
['Love', 'Li', 'Feng', 2, 1005, 100, 8, 5, 4, 1]
del a[2]
a
['Love', 'Li', 2, 1005, 100, 8, 5, 4, 1]
del
can also be used to delete entire variables
del a
# a will not be there
When assigning a variable (or name) in Python, you are creating a reference to the object on the right hand side of the equals sign.
a = [1,2,3,4]
b = a
a.append(100)
print(a)
print(b)
[1, 2, 3, 4, 100] [1, 2, 3, 4, 100]
list.copy()
c1 = a.copy()
c2 = a[:]
a.append(23232)
print(a)
print(c1)
print(c2)
[1, 2, 3, 4, 100, 23232] [1, 2, 3, 4, 100] [1, 2, 3, 4, 100]
The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (last-in, first-out). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index
stack = [3, 4, 5]
stack.append(2)
stack
[3, 4, 5, 2]
stack.pop()
stack
[3, 4, 5]
It is also possible to use a list as a queue, where the first element added is the first element retrieved (first-in, first-out); however, lists are not efficient for this purpose.
To implement a queue, use collections.deque()
which was designed to have fast appends and pops from both ends. For example:
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # Terry arrives
queue.append("Graham") # Graham arrives
queue
deque(['Eric', 'John', 'Michael', 'Terry', 'Graham'])
queue.popleft() # The first to arrive now leaves
queue.popleft() # The second to arrive now leaves
queue
deque(['Michael', 'Terry', 'Graham'])
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
squares = [] # the usual way
for x in range(10):
squares.append(x**2)
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [x**2 for x in range(10)]
print(squares)
new = [x-2 for x in squares]
print(new)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] [-2, -1, 2, 7, 14, 23, 34, 47, 62, 79]
which eventually did this
squares = list(map(lambda x: x**2, range(10)))
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
def isleapyear(year):
"""Check if a given year is a leap year
"""
if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0):
return True
else:
return False
[isleapyear(x) for x in range(2000,2011)]
[True, False, False, False, True, False, False, False, True, False, False]
[x for x in range(2000,2011) if isleapyear(x)]
[2000, 2004, 2008]
[(x, isleapyear(x)) for x in range(2000,2011)]
[(2000, True), (2001, False), (2002, False), (2003, False), (2004, True), (2005, False), (2006, False), (2007, False), (2008, True), (2009, False), (2010, False)]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
which is equivalent to:
combs = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x, y))
combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
matrix
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
[[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
transposed = []
for i in range(4):
transposed.append([row[i] for row in matrix])
transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
zip()
function would do a great job for this use case:list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
A tuple consists of a number of values separated by commas
t = 12345, 54321, 'hello!'
t[0]
12345
t
(12345, 54321, 'hello!')
immutable
, but they can contain mutable objects.u = t, (1, 2, 3, 4, 5)
u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
v = ([1, 2, 3], [3, 2, 1])
v
([1, 2, 3], [3, 2, 1])
Note On output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys. Dictionaries are sometimes found in other languages as associative memories'' or
associative arrays''.
The keys can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can't use lists as keys.
It is best to think of a dictionary as an unordered set of key:value
pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value
pairs within the braces adds initial key:value
pairs to the dictionary; this is also the way dictionaries are written on output.
Dictionary is also very easy to convert to pandas DataFrame
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print(tel)
{'jack': 4098, 'sape': 4139, 'guido': 4127}
dict()
constructor builds dictionaries directly from sequences of key:value
pairs:dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'guido': 4127, 'jack': 4098, 'sape': 4139}
dict(sape=4139, guido=4127, jack=4098)
{'guido': 4127, 'jack': 4098, 'sape': 4139}
list(tel.keys())
['jack', 'sape', 'guido']
sorted(tel.keys())
['guido', 'jack', 'sape']
'guido' in tel
True
'jack' not in tel
False
key:value
pair with del
. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.del tel['sape']
dict
comprehensions can be used to create dictionaries from arbitrary key and value expressions:{x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces {}
or the set()
function can be used to create sets. Note: to create an empty set you have to use set()
, not {}
; the latter creates an empty dictionary.
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # show that duplicates have been removed
{'apple', 'pear', 'orange', 'banana'}
'orange' in basket
True
a = set('abracadabra')
b = set('alacazam')
print(a)
print(b)
{'c', 'b', 'a', 'd', 'r'} {'c', 'm', 'l', 'a', 'z'}
a - b
{'b', 'd', 'r'}
a | b
{'a', 'b', 'c', 'd', 'l', 'm', 'r', 'z'}
a & b
{'a', 'c'}
a ^ b # XOR: exclusive OR
{'b', 'd', 'l', 'm', 'r', 'z'}
a = {x for x in 'abracadabra' if x not in 'abc'}
a
{'d', 'r'}
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
robin the brave gallahad the pure
enumerate()
function.for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
0 tic 1 tac 2 toe
zip()
function.questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.
reversed()
function.for i in reversed(range(1, 10, 2)):
print(i)
9 7 5 3 1
sorted()
function which returns a new sorted list while leaving the source unaltered.basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f)
apple banana orange pear
words = ['cat', 'window', 'defenestrate']
for w in words[:]: # Loop over a slice copy of the entire list.
if len(w) > 6:
words.insert(0, w)
words
['defenestrate', 'cat', 'window', 'defenestrate']
words2 = ['cat', 'window', 'defenestrate']
for w in words2: # No copies.
if len(w) > 6:
words2.insert(0, w)
words2