Python Flashcards Preview

INF3331 > Python > Flashcards

Flashcards in Python Deck (81)
Loading flashcards...
1
Q

change a tuple

A

illegal

2
Q

add element to list

A

a.append(elem)

3
Q

add two lists

A

a + [1, 3]

4
Q

get last list element

A

a[-1]

5
Q

copy index 1, 2 and 3 to sublist

A

a[1:4]

6
Q

delete element with a given index

A

del a[i]

7
Q

remove an element with a given value

A

a.remove(value)

8
Q

find index corresponding to an element’s value

A

a.index(value)

9
Q

test if a value is contained in the list

A

value in a

10
Q

count how many elements that have given value

A

a.count(value)

11
Q

number of elements in list a

A

len(a)

12
Q

the smallest element in a

A

min(a)

13
Q

the largest element in a

A

max(a)

14
Q

add all elements in a

A

sum(a)

15
Q

sort list

A

a.sort() # changes a

16
Q

sort list into a new list

A

sorted(a)

17
Q

reverse list

A

a.reverse() # changes a

18
Q

check if a is a list

A

isinstance(a, list)

19
Q

Print full names

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

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

print name, surname

20
Q

Print indexes and names

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

A

for i, name in enumerate(names):

print i, name

21
Q

evaluate string expressions

A

r = eval(‘x + 2.2’)

22
Q

read a file

A

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

23
Q

write to file

A

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

24
Q

initialize a dictionary

A
a = {'point': [2,7], 'value': 3}
a = dict(point=[2,7], value=3)
25
Q

add new key-value pair to a dictionary

A

a[‘key’] = value

26
Q

delete a key-value pair from the dictionary

A

del a[‘key’]

27
Q

list of keys in dictionary

A

a.keys()

28
Q

list of values in dictionary

A

a.values()

29
Q

number of key-value pairs in dictionary

A

len(a)

30
Q

loop over keys in unknown order

A

for key in a:

31
Q

loop over keys in alphabetic order

A

for key in sorted(a.keys()):

32
Q

check if a is a dictionary

A

isinstance(a, dict)

33
Q

get index of char in string

A

str.find(‘char’)

34
Q

split string into substrings

A

str.split(‘:’)

35
Q

test if substring is in string

A

substring in string

36
Q

remove leading/trailing blanks

A

str.strip()

37
Q

combine list into string with delimiter

A

’, ‘.join(list)

38
Q

file blogging

A

import glob

files = glob.glob(‘*.pdf’)

39
Q

check for directory

A

import os.path

os.path.isdir(myfile)

40
Q

get file size

A

import stat

os.stat(myfile)[stat.ST_SIZE]

41
Q

copy a file

A

import shutil

shutil.copy(myfile, newfile)

42
Q

rename a file

A

import os

os.rename(myfile, ‘newname’)

43
Q

remove a file

A

import os

os.remove(‘filename’)

44
Q

create directory

A

os.mkdir(dirname)

45
Q

create path out of strings

A

os.path.join(os.environ[‘HOME’], ‘py’, ‘src’)

46
Q

remove directory

A

shutil.rmtree(‘myroot’)

47
Q

get filename out of full path

A

os.path.basename(path)

48
Q

traverse directory

A
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
Q

print with variables

A

print ‘%d: %s’ % (index, string)

50
Q

a = [1, 2]
b = a
a is b?

A

True

51
Q

make a copy of list

A

b = a[:]

52
Q

make a copy of dictionary

A

b = a.copy()

53
Q

run stand-alone application

A

from subprocess import Popen, PIPE
p = Popen(cmd, shell=True, stdout=PIPE)
output, errors = p.communicate()

54
Q

read file into a list of lines

A
file = open(filename, 'r')
lines = file.readlines()
55
Q

convert string to float

A

float(str)

56
Q

boolean type

A

bool a = True

57
Q

convert all elements in list to float

A

y = map(float, y)

58
Q

define comparison criterion

A
def comparator(s1, s2):
    # return -1, 0, 1
list.sort(comparator)
59
Q

replace in string

A

str.replace(this, withThis)

60
Q

multi-line string

A

str = “””

“””

61
Q

substring fra string

A

string[1:5]

62
Q

Are string mutable?

A

No, strings (and tuples) are immutable

63
Q

change global variables inside function

A

global varName

64
Q

main-function

A

if __name__ == ‘__main__’:

65
Q

doc string

A

first string in functions, classes, files

66
Q

print doc string

A

> > > print function.__doc__

67
Q

doctest

A
Inside doc string:
"""
>>> function(3)
6.0
"""

import doctest
doctest.testmod(function)

68
Q

run doctest

A

Just run the script!

import doctest
doctest.testmod(function)

69
Q

define class w/ constructor

A
class MyClass(object):
    conter = 0 # static variable
    def \_\_init\_\_(self, i): # constructor
        self.i = i;
70
Q

create object of class

A

obj = MyClass(5)

71
Q

define subclass

A
class SubClass(MyClass):
    def \_\_init\_\_(self, i, j):
        MyClass.\_\_init\_\_(self, i)
        self.j = j
72
Q

public, protected, private

A
a = # public
_b = # non-public
\_\_c = # private
73
Q

class instance: dictionary of user-defined attributes

A

instance.__dict__

74
Q

class name from instance

A

instance.__class__.__name__

75
Q

list names of all methods and attributes in class instance

A

dir(instance)

76
Q

difference between is and ==

A

is checks object identity

== checks for equal contents

77
Q

when is a evaluated as true?

A

if a has
__len__ or
__nonzero__
and the return value is 0 or False

78
Q

list of local variables

list of global variables

A

locals()

global()

79
Q

simple timer

A

import timeit

print timeit.timeit(function, number=100)

80
Q

profiler

A

import profile

profile = profile.run(“func()”)

81
Q

save profiling data to file, read afterwards

A

import profile
profile = profile.run(“func()”, “result.txt”)

import pstats
data = pstats.Stats(“result.txt”)
data.print_stats()