Python Flashcards

(81 cards)

1
Q

change a tuple

A

illegal

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

add element to list

A

a.append(elem)

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

add two lists

A

a + [1, 3]

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

get last list element

A

a[-1]

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

copy index 1, 2 and 3 to sublist

A

a[1:4]

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

delete element with a given index

A

del a[i]

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

remove an element with a given value

A

a.remove(value)

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

find index corresponding to an element’s value

A

a.index(value)

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

test if a value is contained in the list

A

value in a

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

count how many elements that have given value

A

a.count(value)

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

number of elements in list a

A

len(a)

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

the smallest element in a

A

min(a)

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

the largest element in a

A

max(a)

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

add all elements in a

A

sum(a)

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

sort list

A

a.sort() # changes a

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

sort list into a new list

A

sorted(a)

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

reverse list

A

a.reverse() # changes a

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

check if a is a list

A

isinstance(a, list)

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

Print full names

names = ["Ola", "Per", "Kari"]
surnames = ["Olsen", "Pettersen", "Bremnes"]
A

for name, surname in zip(names, surnames):

print name, surname

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

Print indexes and names

names = [“Ola”, “Per”, “Kari”]

A

for i, name in enumerate(names):

print i, name

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

evaluate string expressions

A

r = eval(‘x + 2.2’)

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

read a file

A

file = open(filename, ‘r’)
for line in file:
print line
infile.close()

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

write to file

A

file = open(filename, ‘w’) # or ‘a’ to append
file.write(“””
….
“””)

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

initialize a dictionary

A
a = {'point': [2,7], 'value': 3}
a = dict(point=[2,7], value=3)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
add new key-value pair to a dictionary
a['key'] = value
26
delete a key-value pair from the dictionary
del a['key']
27
list of keys in dictionary
a.keys()
28
list of values in dictionary
a.values()
29
number of key-value pairs in dictionary
len(a)
30
loop over keys in unknown order
for key in a:
31
loop over keys in alphabetic order
for key in sorted(a.keys()):
32
check if a is a dictionary
isinstance(a, dict)
33
get index of char in string
str.find('char')
34
split string into substrings
str.split(':')
35
test if substring is in string
substring in string
36
remove leading/trailing blanks
str.strip()
37
combine list into string with delimiter
', '.join(list)
38
file blogging
import glob | files = glob.glob('*.pdf')
39
check for directory
import os.path | os.path.isdir(myfile)
40
get file size
import stat | os.stat(myfile)[stat.ST_SIZE]
41
copy a file
import shutil | shutil.copy(myfile, newfile)
42
rename a file
import os | os.rename(myfile, 'newname')
43
remove a file
import os | os.remove('filename')
44
create directory
os.mkdir(dirname)
45
create path out of strings
os.path.join(os.environ['HOME'], 'py', 'src')
46
remove directory
shutil.rmtree('myroot')
47
get filename out of full path
os.path.basename(path)
48
traverse directory
``` def myfunc(arg, dirname, files): for filename in files: arg.append(filename) os.path.walk(os.environ['HOME'], myfunc, list) for filename in list: print filename ```
49
print with variables
print '%d: %s' % (index, string)
50
a = [1, 2] b = a a is b?
True
51
make a copy of list
b = a[:]
52
make a copy of dictionary
b = a.copy()
53
run stand-alone application
from subprocess import Popen, PIPE p = Popen(cmd, shell=True, stdout=PIPE) output, errors = p.communicate()
54
read file into a list of lines
``` file = open(filename, 'r') lines = file.readlines() ```
55
convert string to float
float(str)
56
boolean type
bool a = True
57
convert all elements in list to float
y = map(float, y)
58
define comparison criterion
``` def comparator(s1, s2): # return -1, 0, 1 list.sort(comparator) ```
59
replace in string
str.replace(this, withThis)
60
multi-line string
str = """ ... """
61
substring fra string
string[1:5]
62
Are string mutable?
No, strings (and tuples) are immutable
63
change global variables inside function
global varName
64
main-function
if __name__ == '__main__':
65
doc string
first string in functions, classes, files
66
print doc string
>>> print function.__doc__
67
doctest
``` Inside doc string: """ >>> function(3) 6.0 """ ``` import doctest doctest.testmod(function)
68
run doctest
Just run the script! import doctest doctest.testmod(function)
69
define class w/ constructor
``` class MyClass(object): conter = 0 # static variable def __init__(self, i): # constructor self.i = i; ```
70
create object of class
obj = MyClass(5)
71
define subclass
``` class SubClass(MyClass): def __init__(self, i, j): MyClass.__init__(self, i) self.j = j ```
72
public, protected, private
``` a = # public _b = # non-public __c = # private ```
73
class instance: dictionary of user-defined attributes
instance.__dict__
74
class name from instance
instance.__class__.__name__
75
list names of all methods and attributes in class instance
dir(instance)
76
difference between is and ==
is checks object identity | == checks for equal contents
77
when is a evaluated as true?
if a has __len__ or __nonzero__ and the return value is 0 or False
78
list of local variables | list of global variables
locals() | global()
79
simple timer
import timeit | print timeit.timeit(function, number=100)
80
profiler
import profile | profile = profile.run("func()")
81
save profiling data to file, read afterwards
import profile profile = profile.run("func()", "result.txt") import pstats data = pstats.Stats("result.txt") data.print_stats()