Python Quiz#

Lists#

[2]:
import copy

a = [1]
b = [0, a]
c = copy.copy(b)

print(c is b)
print(c[1] is b[1] is a)

# c = copy.copy(b) is equivalent to c = b[:] and creates a shallow copy
False
True
[4]:
import copy

a = [1]
b = [0, a]
c = copy.deepcopy(b)

print(c is b)
print(c[1] is b[1] is a)

c[1][0] = 'Y'
a[0] = 'X'

print(b)
print(c)

# c = copy.deepcopy(b) creates a deep copy of b, duplicating any internal references. c[1] no longer points to a
False
False
[0, ['X']]
[0, ['Y']]
[5]:
text = 'a b c    d'
words = text.split(None, 2)
print(words)
['a', 'b', 'c    d']
[6]:
x = [0, 1, 2, 3]
x[1:2] = []
print(x)
# Slice notation x[1:2] = [] can be used to remove elements from a list
[0, 2, 3]
[11]:
# What this code outputs and why?

x = [0, 1, 2, 3]
x[::2] = [7, 8]
print(x)
[7, 1, 8, 3]

# You can assign to extended slices, but the list on the right hand side of the statement must contain the same number of items as the slice it is replacing.
[7, 1, 8, 3]
[11]:
[7, 1, 8, 3]
[13]:
x = [0, 1, 2]
x.append([3 ,4])
print(x)
print(x[3])

# append method always adds a single element to a list
[0, 1, 2, [3, 4]]
[3, 4]
[15]:
# Alternative to add list in the end list
x = [0, 1, 2]
x.extend([3, 4])
print(x)

# extend method only receives iterables, unlike append
[0, 1, 2, 3, 4]
[19]:
a, *b, c = [1, 2, 3, 4, 5]
print(a, b, c)
# Tuple unpacking
1 [2, 3, 4] 5
[28]:
# Filtering Elements from List
x = [1, 0, 2, 0, 3, 0]
x = [i for i in x if i != 0]
print(x)

# This list comprehension removes all instances of 0 from a list.
[1, 2, 3]

Tuples#

[25]:
x = 1, 2
print(type(x))

# Tuples can be created without parentheses
<class 'tuple'>
[18]:
x = (i**2 for i in range(4))
print(x)

# This is a generator expression. There is no tuple comprehension
<generator object <genexpr> at 0x7f2f06fb6c78>
[ ]:
x = tuple(i**2 for i in range(4))
print(x)
# For tuple comprehension, use the tuple() function.
[27]:
x = ([],)
x[0].append(2)
x[0].append(3)
print(x)


# You can append to a list inside a tuple, a list is mutable.
([2, 3],)

Dictionaries#

[16]:
data = {'a':1, 'a':2, 'c':3}

print(data['a'])

# Dictionary keywords are unique. When you add a keyword more than once, the last value overwrites the previous.
2
[17]:
data = {'a':1, 'b':2}
data[1] = 4
print(data)

# Integers can serve as dictionary keywords. If no keyword exists, a new one is created.
{'a': 1, 'b': 2, 1: 4}
[ ]:
data = {x:'abc'[x] for x in range(3)}
print(data)

# You can use dictionary comprehension to create a dictionary

String#

[ ]:
str = '-'
seq = ['a', 'b', 'c']
x = str.join(seq)
print(x)

# String join method uses the string as a separator for a list of strings and returns a string.

Lambda Functions#

[24]:
func = lambda: 1 if x else 2

x = True
print(func())
y = False
print(func())

# lambda uses variables from external scope
1
1

Functions#

[26]:
def out():
    global x
    x = 5


out()
print(x)


# You can use global to create global variables inside a function, unlike nonlocal.
5