Basic Python Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Are Python lists mutable (can they be changed after creation)?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Is everything in Python an Object?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Do Python Collection indexes start at 0?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Is Python case sensitive?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you do a 1 line comment in Python?

A

Use the ‘#’ symbol either at start of line, or inline

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can you have more than one statement on a line in Python?

A

Yes. Use the semi-colon to separate statements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does dynamic typing mean?

A

Variable names can point to objects of any type e.g.

x = 1 .. x is integer
x = ‘hello’ … x is string
x = [1, 2, 3] … x is list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

In Python are variables containers or pointers?

A

Pointers e.g. x = 4, the variable x is a pointer that points to some other bucket containing 4

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Give a comparison of a mutable type v an immutable type assignment

A
x = [1, 2, 3] #List
a = 1 # int
y = x  # y is a List {1, 2, 3]
b = a # b is an int 1

x.append(4)
print(y) … y = [1, 2, 3, 4] # because Lists are mutable, variable y is still a pointer to the same bucket that x points to, and so y’s value is updated

a = 2
print (b) … b = 1 # because ints are immutable, and so the assignment of a =2, forces a to become pointer to a new bucket. The previous bucket containing 1 cannot be updated, and so because b points there, the value of b still = 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Is a Dictionary mutable?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Is a Set mutable?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Is a String mutable?

A

No, it is immutable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Is a Tuple mutable?

A

No, it is immutable e.g.

t = (1, 2, 3)
t[1] = 4 # not valid
t.append(4) # not valid

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Is an Int or Float mutable?

A

No, there are immutable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the standard Python Boolean operators?

A

and, or , not

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are identity operators?

A

is, is not … used to identify identical objects e.g.

a = [1, 2, 3]
b = [1, 2, 3]

a == b # True
a is b # False … a and b are not the same objects even though they contain the same value.

a is b returns True if we do …

a = [1, 2, 3]
b = a
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are membership operators?

A

Membership operators check for membership within compound objects e.g.

1 in [1, 2, 3] #True
2 not in [1, 2, 3] # False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is deep and shallow copying?

A

In Python assignment statements do not copy objects they create bindings between a target and an object. With mutable objects sometimes users want to create ‘real’ copies of the object, so that they can be changed without affecting the original.

Deep Copying ( copy.deepcopy(object) ) … a copy of the object is copied to another object. Any changes made to the copy do not reflect in the original object. Slower than shallow copy.

Shallow Copying ( copy.copy(object) ) … a copy of the object is made but it is populated with references to the child object, rather than actual copies. Shallow copying is also what happens when using factory functions e.g. new_list = list(orig_list).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What terminates a statement in Python?

A

The end of the line

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How can you continue a statement over 2 lines in Python?

A

Use the ‘' marker or enclose statement within brackets e.g.

x = (1 + 2 + 3 + 4 +
5 + 6 + 7 + 8) # this second type is recommended

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is indentation used for in Python?

A

To denote code blocks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What symbol is used to denote an indented code block?

A

A colon

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How can you check the type of a Python object?

A

type(x)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is exponential notation?

A

Where numbers are stored used the exponential format e.g. 5e-6, which equals 0.000005 or 1.4e6 which equals 1400000.00

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is one method of concatenating strings?

A

string1 + string2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How can you access individual elements of a string?

A

string1[x] where x is an element index. Strings are Lists, and so can be iterated through.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is the None type?

A

None type is a special Python type which has a single possible value - None.
Used as the default return type for functions e.g.

return_value = print(‘abc’)
print(return_value)
… value returned is None

Not to be confused with NaN # a Numpy/Pandas construct

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Are Lists ordered?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How do you append values to a list?

A

list1 = [1, 2, 3]
list1.append(4)

Can also concatenate to a list via …
list1 + [4, 5, 6]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is a compound object?

A

List, Dictionary, Tuple, Set

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Can compound objects e.g. Lists contain objects of mixed type?

A

Yes e.g.

list1 = [1, ‘hello’, 3.4, [‘another’, ‘list’]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Does python used zero-based indexing?

A

Yes e.g.

string1[0] returns the first element of the string object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

How do you access the last element of a list?

A

list1[-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is the difference between indexing and slicing for compound objects?

A

Indexing is a means of fetching a single value from the list, slicing is a means of accessing multiple values in sub-lists

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

How can you traverse a list backwards?

A

a[::-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How does list slicing work?

A

It uses a colon to indicate the start point (inclusive) and end point (non-inclusive) of the sub-array. For example, to get the first three elements of the list, we can write: L[0:3]

37
Q

What does leaving out the indexes in List slicing achieve?

A

list1[1, 2, 3, 4]

list1[:] # returns entire list from start to finish
list1[1:] # returns everything from second element to the end
list1[:3] # returns everything from first element to the third element (remember zero based indexing)

38
Q

What is step size in List slicing?

A

The optional third integer in list slice arguments which specifies the step size to use when returning elements from the list

39
Q

Can you use List slicing to set list elements as well as return them?

A

Yes e.g. L[1:3] = [55, 56]

40
Q

How are Tuples defined?

A

With parentheses rather than brackets

tuple1 = (1, 2, 3)

also possible as: tuple1 = 1, 2, 3

41
Q

What is a common use of Tuples

A

As a return type from function to return multiple items

42
Q

How are dictionaries defined?

A

With curly brackets and colon e.g.

d1 = {‘key’: value, ‘key’: value}

43
Q

How are dictionary elements accessed?

A

Items are accessed and set via the indexing syntax used for lists and tuples, except here the index is not a zero-based order but valid key in the dictionary:

numbers[‘two’] # accesses the value with key ‘two’ in dictionary numbers

44
Q

Are dictionaries ordered?

A

Keep in mind that dictionaries do not maintain any sense of order for the input parameters; this is by design. This lack of ordering allows dictionaries to be implemented very efficiently, so that random element access is very fast, regardless of the size of the dictionary

45
Q

What is a conditional statement?

A

if-then-else … python uses elif and colons e.g.

if x == 0:
    print(x, "is zero")
elif x > 0:
    print(x, "is positive")
elif x < 0:
    print(x, "is negative")
else:
    print(x, "is unlike anything I've ever seen...")
46
Q

What is syntax of for loop?

A

for i in iterator:
do something

e.g.
for N in [2, 3, 5, 7]:
print(N, end=’ ‘) # print all on same line

47
Q

Explain use of range and enumerate with for loop

A

range provides a list of integers to iterate through
enumerate iterators through a list and provide index and value e.g.

for n in range(10) # provides list of 10 numbers from 0->9

list1=[1, 2,’hello’]
for i,j in enumerate(list1):
print i, j # iterate through elements in list1

48
Q

What are break and continue in context of loops?

A

Used to fine-tune execution of loops.

The break statement breaks-out of the loop entirely

The continue statement skips the remainder of the current loop, and goes to the next iteration

49
Q

How do you define a function in Python?

A
def functionName(n):
    some stuff
    return x
50
Q

How do you declare default values for function arguments?

A

def functionName(n, x=10, y=20):

51
Q

What are*args and **kwargs used for?

A

Sometimes you might wish to write a function in which you don’t initially know how many arguments the user will pass. These special forms catch all arguments passed.

Here it is not the names args and kwargs that are important, but the * characters preceding them. args and kwargs are just the variable names often used by convention, short for “arguments” and “keyword arguments”.

52
Q

Describe use of *args

A
def catch_all(*args):
    print("args =", args)

catch_all(1, 2, 3)

args = (1, 2, 3)

The operative difference is the asterisk characters: a single * before a variable means “expand this as a sequence”

53
Q

Describe use of **kwargs

A
def catch_all(**kwargs):
    print("kwargs = ", kwargs)

catch_all(a=4, b=5)

kwargs = {‘a’: 4, ‘b’: 5}

The operative difference is the asterisk characters: a double ** before a variable means “expand this as a dictionary”.

54
Q

What is a lambda function?

A

It is a way of defining an anonymous, short, one-off function e.g.

add = lambda x, y: x + y
add(1, 2)

55
Q

How do you catch exceptions in Python?

A

try:
something
except:
catch errors here

56
Q

How do you raise an error in Python?

A

Use the raise statement e.g.

raise RuntimeError("my error message")
raise ValueError("N must be non-negative")
57
Q

What is the try, except, else, finally clause?

A
try:
    print("try something here")
except:
    print("this happens only if it fails")
else:
    print("this happens only if it succeeds")
finally:
    print("this happens no matter what")

The utility of else here is clear, but what’s the point of finally? Well, the finally clause really is executed no matter what: I usually see it used to do some sort of cleanup after an operation completes.

58
Q

What is the iter function?

A

This function checks to see if an object has an iterator interface. The iter object is a container that gives you access to the next object for as long as it’s valid e.g.

I = iter([2, 4, 6, 8, 10])
print(next(I))

59
Q

zip Iterator … explain

A

When you have multiple lists you wish to iterate over simultaneously use the zip iterator to ‘zip’ together iterators e.g.

L = [2, 4, 6, 8, 10]
R = [3, 6, 9, 12, 15]
for lval, rval in zip(L, R):
print(lval, rval)

60
Q

What happens when using the zip iterator on iterators of different lengths?

A

The shortest iterator determines the length of the zipped output

61
Q

map Iterator … explain

A

The map iterator takes a function and applies it to the values in an iterator e.g.

# find the first 10 square numbers
square = lambda x: x ** 2
for val in map(square, range(10)):
    print(val, end=' ')
62
Q

filter iterator … explain

A

Similar to map iterator, but only passes-through values for which the filter evaluates to True e.g.

# find values up to 10 for which x % 2 is zero
is_even = lambda x: x % 2 == 0
for val in filter(is_even, range(10)):
    print(val, end=' ')
63
Q

What is a List Comprehension?

A

It’s a way to compress a list-building for-loop into a single short readable line

64
Q

What is the syntax of a basic List Comprehension?

A

[n ** 2 for n in range(12)]

This creates a list with the square of every value from 0 to 11

65
Q

How do conditionals in List Comprehensions work?

A

Conditionals on the Iterator:

[val for val in range(20) if val % 3 > 0]

Conditionals on the Value

[val if val % 2 else -val for val in range(20) if val % 3]

66
Q

Are List Comprehensions the only type of Comprehension?

A

No. You can have Set and Dictionary Comprehensions … but not Tuple ones (I think)

67
Q

What is a generator expression?

A

A generator expression is essentially a list comprehension in which elements are generated as-needed rather than all at-once

(n ** 2 for n in range(12))

68
Q

What is a generator a recipe for?

A

A recipe for producing values.

When you create a list, you are actually building a collection of values, and there is some memory cost associated with that. When you create a generator, you are not building a collection of values, but a recipe for producing those values.

The difference is that a generator expression does not actually compute the values until they are needed. This not only leads to memory efficiency, but to computational efficiency as well! This also means that while the size of a list is limited by available memory, the size of a generator expression is unlimited!

69
Q

Can a generator be used multiple times?

A

No

70
Q

What should List Comprehensions be used for?

A

They are best used to create relatively simple lists. Using a for loop can be better for more complicated situations.

71
Q

What is import used for?

A

For loading built-in and 3rd party modules

72
Q

Explain an explicit module import

A

Explicit import of a module preserves the module’s content in a namespace e.g.

import math
math.cos(math.pi)

73
Q

Explain an explicit module import by alias

A

For longer module names, it’s not convenient to use the full module name each time you access some element. For this reason, we’ll commonly use the “import … as …” pattern to create a shorter alias for the namespace.

import numpy as np

74
Q

Explain explicit import of module contents

A

Sometimes rather than importing the module namespace, you would just like to import a few particular items from the module.

from math import cos, pi
cos(pi)

75
Q

What are the potential problems with implicit import of module contents?

A

It is sometimes useful to import the entirety of the module contents into the local namespace. e.g. from math import *

This pattern should be used sparingly, if at all. The problem is that such imports can sometimes overwrite function names that you do not intend to overwrite, and the implicitness of the statement makes it difficult to determine what has changed. Python’s built-in sum function could be overwritten by the numpy version and give different results to expected.

76
Q

How can you swap variables?

A

a, b = b, a

77
Q

How do you use the list constructor?

A

list(iterable)

list(‘hello’) # returns [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
list((1,2,3)) # returns [1,2,3] - turns tuple into list

78
Q

What are two names for methods with double underscores for prefix and suffix in the method name?

A

magic methods or dunder (double underscore) methods

79
Q

What is the __init__ method normally used for?

A

This is used for Python classes, usually as a type of constructor to declare instance variables

80
Q

In OOP what is encapsulation?

A
  1. Objects group variables (state) and methods into a single unit (the object)
  2. Objects hide a class internal data to clients from directly accessing it.
81
Q

Does Python allow private variables?

A

No, all Python variables are public … but …

82
Q

How does Python mimic private variables in OOP?

A

Naming conventions. The use of a single underscore in front of a variabl/method is used to signify that the caller shouldn’t access it

83
Q

In OOP what is abstraction?

A

Abstraction is the process of moving characteristics from something in order to reduce it to a set of essential characteristics. Abstraction is used in OOP to model objects using classes and omit unnecessary details.

84
Q

In OOP what is polymorphism?

A

Polymorphism is the ability to present the same interface (method) for different underlying forms.

85
Q

In OOP what is Inheritance?

A

Inheritance in OOP is when a class is created it can inherit methods and variables from another parent class - although these values can be overwritten.

86
Q

In OOP what is the difference btw a Class and Instance variable?

A

Instance variable are attached to specific objects that are created/instantiated from a class. Class variables belong to the class itself, and can be used to share data between all instances of a class - without needing global variables.

87
Q

Give some examples of magic (dunder) methods?

A

Every class in Python inherits from a parent class called Object, and Python utilises methods inherited from Object in different situations. Some of these are magic methods such as:

__init__ initialising state of an Object
__repr__ used for a printable representation of an object
__add__

88
Q

What is pickle?

A

Pickel is used to serialize and de-serialize object. Turns an objects into a byte/character stream so that it can be written to file and stored/transferred. Specific to Python.

Danger that pickled stream could be hacked.
JSON is a better option as it’s language-independent, and more secure and faster/