Python Flashcards Preview

INF3331 > Python > Flashcards

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

change a tuple

illegal

2

add element to list

a.append(elem)

3

add two lists

a + [1, 3]

4

get last list element

a[-1]

5

copy index 1, 2 and 3 to sublist

a[1:4]

6

delete element with a given index

del a[i]

7

remove an element with a given value

a.remove(value)

8

find index corresponding to an element's value

a.index(value)

9

test if a value is contained in the list

value in a

10

count how many elements that have given value

a.count(value)

11

number of elements in list a

len(a)

12

the smallest element in a

min(a)

13

the largest element in a

max(a)

14

add all elements in a

sum(a)

15

sort list

a.sort() # changes a

16

sort list into a new list

sorted(a)

17

reverse list

a.reverse() # changes a

18

check if a is a list

isinstance(a, list)

19

Print full names

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

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

20

Print indexes and names

names = ["Ola", "Per", "Kari"]

for i, name in enumerate(names):
print i, name

21

evaluate string expressions

r = eval('x + 2.2')

22

read a file

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

23

write to file

file = open(filename, 'w') # or 'a' to append
file.write("""
....
""")

24

initialize a dictionary

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

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: