General python Flashcards
How do you get a new blank row into code?
\n , print()
What is the escape character?
\
What does \ do?
Announces that the string should be paused and that the character after means something
How do you print the character \
print(“\”)
What happens when you pass muliple arguments to a print function
1) It combines them all on one line
2) It puts a small between the outputted arguments
What is a positional argment?
The location determines what it does
How do you use keyword arguments?
1) keyword = value
2) after positional arguments
What does the default end keywork argument do in print
\n
How do you alter the default behaviour of print to insert a space between arguments?
sep =
What is a literal?
Data you can determine the value of without any additional knowledge e.g. 123 vs c
What are the 2 ways to show quotation marks in Python
" or use ‘’ instead of “”
How do you encode ‘to the power of’
**
What does print(6/2) give you?
A float
What does // do?
Integer division
What happens when the result of // is not an integer?
Rounds to the lower number (ie. floor division)
What is the result of print( 6 // - 4)?
-2
What type does the % operation result in?
Float
what is a unary and a binary operatory
Binary expect 2 arguments, unary expects 1
Is python predominantly right side or left side binding?
Left side
What is the exception to left side binding
Exponentiation
What is the order of priority of operators?
1) + - (unary)
2) **
3) * / %
4) + - (binary)
5) , >=
6) ==, !=
What does a variable contain?
A name and value
How do you evaluate the square root of something?
** 0.5
What does input() store values as?
A string
What do you need to do to get input usable with operators?
float()
What does isna() return?
Boolean series
How do you count how many missing values?
df.isna().sum()
How do you get a dataframe into a list?
df.values.flatten()
How do you get summary statistics by row?
1) data = pd.DataFrame()
2) var = df.mean(axis = 1)
3) data[‘var’] = var
What is the keyboard shortcut to see all methods?
tab after the .
What is the keyboard shortcut to see the arguments available?
shift and tab
What is the difference between a method and an attribute?
Attribute describes and has no parentheses, methods have parentheses
Describe ==
Binary, left binded
In python what are the comparison operators?
==, !=, >, =, <=
What has higher priority: == or >=
> =
What is the difference between if and elif?
If will always be evaluated, elif and else stop once something is found to be true (and assumes the previous thing was false)
What does range(100) do?
0 to 99
What does range(2,8) do?
2 to 7
What does range(2,8,3)
2, 5
What does break do?
Exits the loop immediately
What does continue do?
Behaves as if the programme has reached the end of the body of the loop and starts the next turn
What is the difference between break and continue?
Break exits the loop, continue goes to start the next loop immediately
What are the logical operators?
and
or
not
What are the logical operators vs the comparison operators?
Comparison >= > !=
Logical and or not
What has higher priority; comparison operators or logical?
Comparison
Is and binary or unary?
binary
What has higher priority; and or or?
and
What does not do?
It turns false into true and true into false?
What priority is not equivalent to?
unary + and -
What are the bitwise operators?
& | ~ ^
Which are the logical operators and which are the bitwise operators?
Logical: and, or, not
Bitwise: & | ~ ^
What is the difference between | and ~ ?
needs at least 1 1 - ~ needs exactly 1 1
Do bitwise operators need integers or flats?
integers
If a variable is 5, is it true or false?
True - anything that is not zero is true
What is the difference between logical and bitwise operations?
Bitwise takes the bit representation of the number and then compares each pair of bits separately
How do you use an abbreviated form of bitwise operators?
x = x & y is x &= y
How do you replace an item in a list?
listname[index value] = newvalue
what is del?
and instruction not a funcction
how do you get the last item in the list?
list[-1]
What is a method versus a function?
A method is a kind of function but it is owned by the data it works for and can change the internal state of the data
How do you add to a list?
Append (adds to the end)
Insert (you specific the location, and everything moves to the right)
Can you use list[new index] to add to a lits?
no
How do you use a for loop to add up all items in a list?
list = [1,2,3,4,5] total = 0
for i in list:
total += i
print(total)
How do you swap the variables in a list?
var1 = 4 var2 = 6
var1, var2 = var2, var1
Is a list ordered or unordered?
Ordered
Where does mylist[:end] start?
0
How do you copy the full list?
mylist[:]
How do you remove some items of a list?
del mylist[:4]
Does using del create a new list?
no
How do you delete a list contents?
del mylist[:]
How do you delete a list?
del mylist
How do you work out if something is in a list?
in or not in
What is the difference between:
list2 = list1
list2 = list1[:]
The second copies the contents, the first points to the location of list 1 so if you change list it is refleccted
Where do funcitons come from?
Python (built in), modules, code
What is special about a parameter?
It only exists inside a function
Assigning a value to it only happens specifying an argument when invoking the function
Can a variable and a parameter be named the same?
Yes
What are the ways ways to pass parameters?
Positional and keyword
How do you get a function to insert default value for a parameter?
def function(keyword = ‘default’)
Can you overwrite a default parameter in a function?
Yes
What comes first, positional or keyword arguments?
Positional
How many types of return are there?
Return without an expression
Return with an expression
What does return without an expression do?
Stop the funcions activity on demand and return to the point of invocation
What does return with an expression do?
Stops the functions execution and then evaluates the expression’s value and return the functions result
What is return with an expression
Something after the return instruction
What must you do to see the return with an expressions results?
Assign it to a variable and print it
What is None?
A keyword?
What happens when a function doesn’t return a certain value using return with an expression?
Returns None
Can you pass a list to a function?
Yes
How does insert work?
Add an item to the list at a specific value list.insert(0,i)
Does a variable defined outside the body of a function exist inside?
Yes
What is the exception to a variable being read from outside the function?
A variable existing outside a function has a scope inside the functions’ bodies, excluding those of them which define a variable of the same name.
Does a function receive an argument or an arguments value?
Arguments value
Can you change a paramters value?
Yes
True or false: A variable that exists outside a function has a scope inside the function body
True
True or false: A variable that exists outside a function does not have scope inside the function body
False
How do you get a variable to be applicable outside a functions body?
global var
What is mutable and immutable data?
Immutable cannot be chnaged
What is a sequence?
A sequence type is a type of data in Python which is able to store more than one value (or less than one, as a sequence may be empty), and these values can be sequentially (hence the name) browsed, element by element.
What is the syntax for a tuple?
tuple1 = (1, 2, 4, 8) tuple2 = 1., .5, .25, .125
If you print:
tuple1 = (1, 2, 4, 8)
tuple2 = 1., .5, .25, .125
What do you see?
(1, 2, 4, 8)
1.0, 0.5, 0.25, 0.125
Can tuple elements be of different types?
Yes. a tuple’s elements can be variables, not only literals. Moreover, they can be expressions if they’re on the right side of the assignment operator.
Can a tuple be empty?
Yes
How do you create an empty tuple?
emptyTuple = ()
What do you have to do to create a one element tuple?
oneElementTuple1 = (1, ) oneElementTuple2 = 1.,
Add a comma to distinguish it from single value
What happens if you + tuples together?
It joins them together
What happens if you * a tuple?
It multiples them
What works on tuples?
len()
+
*
In and not in
Is a dictionary a sequence?
No
Is a dictionary mutable?
yes
What is a dictionary?
This means that a dictionary is a set of key-value pairs.
Keys in a dictionary can be the same: T or F?
False
What kinds of data can be in dictionary/
Anything except lists
What do len for a dictionary give you?
The number of key-value elements
What is a dictinoary syntax?
dictionary = {“cat” : “chat”, “dog” : “chien”, “horse” : “cheval”}
The list of pairs is surrounded by curly braces, while the pairs themselves are separated by commas, and the keys and values by colons.
Is a dictionary ordered or unordered?
Unordered
Are keys in a dictionary case sensitive or not?
Yes
Can you use a for loop on a dictionary?
No
How can you get a for loop to work on on dictionary?
The first of them is a method named keys(), possessed by each dictionary. The method returns an iterable object consisting of all the keys gathered within the dictionary. Having a group of keys enables you to access the whole dictionary in an easy and handy way.
How do you extract bits out of dictionaries?
.items()
.values()
.keys()
What data types does dict.items() return?
A tuple
How do you replace a value within a dictionary?
dict[‘key’] = ‘new value’
How do you add a new key, value pair to a dictionary?
dict[‘new key’] = ‘value’
or
dict.update({‘duck’: ‘canard’})
With lists can you assign a value to a non existnent index?
No
How do you remove a key from a dictionary?
del dict[‘key’]
What can you do to edit a dictionary?
Update values - dict[‘original’] = ‘new’
Add new values dict[‘new key’]
Delete - del dict[‘key’]
How can items be added to a list?
Append - if a list, adds the list to the list
Extend - adds individual elements
How do you create a tuple?
(1,2,3)
How do you create a one element tuple?
(1,) with a comma otherwise a variable is created
Can you access elements of a tuple by indexing?
Yes
How do you create an empty tuple?
()
What are tuples?
Immutable and ordered/
Can you iterate over a tuple?
Yes
How do you work out if something is in a tuple?
print( 5 in tup)
in or not in
Can you join or mutliple tuples?
Yes
How do you convert an existing element to a tuple?
tuple(lst)
How do you iterate over a dictionary?
for keys, values in dict1.items():
print(keys, values)
What can you do to check if a key is in a dictionary?
if “key” in dict:
print(“yes”)
How do you delete an item from a dicctionary?
del dict1[‘key1’]
What is the difference between clear and delete for dictionary/
clear removes the items, delete actually gets rid of it
How do you create a dictionary from another data type?
dict()
How do you make range go negative
You must specify the last argument to be -1 otherwise it won’t work
What data type do you get from this?
tup[0:3]
Tuple
What data type do you get from this?
tup = (1,2,3)
tup[1]
integer
Why is this bad? From math import *
Because every function is brought into the glboal scope and could conflict with your variables
What does from maths import mean enable you to do?
Use mean() without having to do maths.mean()
Is a tuple immutable?
Yes but you can overrite it - it points to a new object
How do you get the unique refence of an object?
Id()
Do you need () for a tupe?
No
How do you create a single item tuple?
(‘Red’,)
Tuple or string? (‘Red’)
String - for it to be a tuple it would have to be (‘Red’,)
How do you access elements of a tuple?
Square brackets - just like lists
Tuple1 = (10,20,30). Is tuple1 the object or is (10,20,30)?
(10,20,30) is the object
Tuple1 = (10,20,30) and then tuple 2 = Tuple 2. If you then modify Tuple1, does tuple 2 change?
No because tuples are immutable. MOdifying tuple1 creates a new object whereas tuple2 points to the original object
If you append a tuple to a list what happens?
The nubmers are added to to the end of the list (as a list)
Can tuples have mutable objects?
Yes (1,2,[‘hello’, ‘bye’])
If you modify a mutable oject within a tuple, does it create a new object?
No
How do you unpack the tuple?
x, y = (‘Amanda’,[1,2,3])
What does enumerate do?
Products a sequence of tuples with the index and item of the list.
How do you get an output like this?
0: red
1: white
3: blue
for index,value in enumerate([‘red’,’white’,’blue’]):
print(f’{index}: {value}’)
How do you delete items from a list?
del numbers[-1]
Using del - can you delete items from a list, a whole variable or both?
Both
How do you select every other item from a list?
ls[::2]
Sorted() or ls.sort(). One is method one is a fuction, which way around?
Sorted is a built in function, sort is method
ls.sort() - does it happen in place?
Yes
Can you use sorted() on immuatable types?
Yes but you have to assign it to a new variable name
Sorted() vs ls.sort() which one is in place?
ls.sort() is in place
What happens if you mix caps and non caps when sorting?
It might not come alphabetically as items are sorted lexigraphically
How do you find the location within an item in a list?
list.index(5)
What do you use to evaluation if something is contained in a list?
in
1000 in numbers
False
How do you generate a list using rangewithout using append?
list comprehension
list = [i for i in range(0,6)
How do you generate a list only if certain conditions are met
list = [i for i in range(0,6) if i % 2 != 0]
What is the difference between list comprehension and generator expressions?
List comprehension is greedy - it means that the output has to be generated immediately. Genetaor expressions us lazy evaluation - values are produced on demand
List is []
Generator is ()
what is filter?
An inbuilt higher order function (can take other functions)
How do you use filter?
list(filter(somefunction, the item to filter)
The somefunction can either be a function name or lambda e.g.
List(filter(lambda x : ( x > 4 ) == True, somelist)
What is the structure of a lambda expression?
lamba x: x % 2 != 0
Do map and filter actually return the sequences of elements?
No it returns an iterator - you have to iterate over the object to get the sequence of values. list() does this
When do you use map versus filter?
Map when you want to do something to every element, filter when you want to filter on the elements
What does zip do?
Combines parts of different lists / tuples
If you create a list of lists - do the rows have to have the same number of columns?
No - jagged array
If you want to index a multidimensional list, what comes first row or column?
Row
How do you index a multidimensional list? a[1,2] or a[1][2]
a[1][2]
Can the keys of a dictionary be mutable?
No
What does len of a dictionary reveal?
The number of key value pairs
What is the difference between del x and x.clear()
Del removes the variable name, clear keeps the variable name
What does dictionary.items() give you?
An iterator which you can iterate over - gives a tuple of key value pairs
Is a dictionary mutable?
Yes
How do you add a new dicitonary key value pair?
dict[‘new label’]
What order does the dictionary show?
The order they were added
How do you remove an element from a dictionary?
del dict[‘element’]
When you in to search for an item in a dictionary - does it look at keys, values or both?
keys
What is the opposite of in
Not in
What does this do? print(i, end = ‘ ‘)
Prints items on one line with a space between
What can you use to act as a word counter?
from collections import Counter
How can you update a dctionary on mass
dictionary.update({})
dictionary.update({}) or dictionary update(key = value)
Either works
Can you pass a tuple to dictionary.update?
Yes
What is the difference between a set and dictionary?
{} but not key value pair in set. Items in sets are not in the order they are inserted in
Can you have duplicates in a set?
No
How do you create a set?
{} with a sequence of values or set()
How do you create an empty set?
set(), {} won’t work
Are sets mutable or immutable?
Mutable but there is a frozen set which is immutable
When comparing sets, does the order of the items matter?
No
What does < do when comparing sets?
Tests if it is sub set
What will this output? {1,2,3}
False, there must be fewer elements in the left hand one
What is the difference between < and issubset()?
issubset() will evaluate to true if the sets are equal
How do you merge 2 sets?
or union()
How do you return only the overlapping items between 2 sets?
& or intersection()
How do you get items that are only in one set (the left one)
- or difference()
How do you get the items that are not common across both sets?
^ or symmetric_difference
How can you change elements in set?
.add() .remove()
What is the structure to use map?
List(map(lambda x: x*2, thelist))
Can you use map() or do you need to do something else?
It produces something you can iterate over so you need to use list()