Python Flashcards
change a tuple
illegal
add element to list
a.append(elem)
add two lists
a + [1, 3]
get last list element
a[-1]
copy index 1, 2 and 3 to sublist
a[1:4]
delete element with a given index
del a[i]
remove an element with a given value
a.remove(value)
find index corresponding to an element’s value
a.index(value)
test if a value is contained in the list
value in a
count how many elements that have given value
a.count(value)
number of elements in list a
len(a)
the smallest element in a
min(a)
the largest element in a
max(a)
add all elements in a
sum(a)
sort list
a.sort() # changes a
sort list into a new list
sorted(a)
reverse list
a.reverse() # changes a
check if a is a list
isinstance(a, list)
Print full names
names = ["Ola", "Per", "Kari"] surnames = ["Olsen", "Pettersen", "Bremnes"]
for name, surname in zip(names, surnames):
print name, surname
Print indexes and names
names = [“Ola”, “Per”, “Kari”]
for i, name in enumerate(names):
print i, name
evaluate string expressions
r = eval(‘x + 2.2’)
read a file
file = open(filename, ‘r’)
for line in file:
print line
infile.close()
write to file
file = open(filename, ‘w’) # or ‘a’ to append
file.write(“””
….
“””)
initialize a dictionary
a = {'point': [2,7], 'value': 3} a = dict(point=[2,7], value=3)
add new key-value pair to a dictionary
a[‘key’] = value
delete a key-value pair from the dictionary
del a[‘key’]
list of keys in dictionary
a.keys()
list of values in dictionary
a.values()
number of key-value pairs in dictionary
len(a)
loop over keys in unknown order
for key in a:
loop over keys in alphabetic order
for key in sorted(a.keys()):
check if a is a dictionary
isinstance(a, dict)