Object Types Flashcards
What are the built-in object types?
Numbers, strings, lists, dictionaries, tuples, files, sets
For a sequence type, what does the [index] operator do?
Returns the index-th element. Zero-based.
For a sequence type, what does the [-index] operator do?
Returns items from the end of the sequence. -1 is the last item, and so on.
How do you create slices with sequences?
S[1:3]
How do you get the length of a string?
len(S)
How do you get everything from the 2nd character to the end?
S[1:]
How do you concatenate strings?
s1 + s2
How do you create repeated strings
‘Spam’ * 8
Are strings mutable?
Nope. Modify, then copy.
How do you find the position of substrings?
S.find(‘pa’)
How do you find and replace in strings?
S.replace(‘pa’, ‘xyz’)
How do you remove whitespace from the right of a string?
S.rstrip()
How do you get a list of attributes for an object?
dir(object)
What do you import to do pattern matching?
import re
What is a list?
A mutable sequence.
How do you initialize a list?
L = [a, b, c]
How do you add an element to the end of a list?
L.append(ele)
How do you remove an element from the list?
L.pop(position)
How do you sort a list?
L.sort()
How do you reverse the order of a list?
L.reverse()
What is nesting?
containing one object inside another. A list that contains lists, for example.
What are list comprehensions?
Complicated but probably useful for matrix operations. Out of scope.
What is a dictionary?
A set of key->value mappings.
How do you initialize a dictionary?
D = {‘key1’, ‘value1’, ‘key2’, ‘value2’ }
How do you retrieve a key’s value from a dictionary?
D[‘key’]
How do you create a new key/value pair in a dictionary?
Just assign it as D[‘key’] = ‘value’
How do you test for an object not being in a dictionary?
if not ‘f’ in D:
code
What is a tuple?
An immutable list, used to represent fixed collections of items.
How do you code tuples?
(a, b, c). Contrast with a list: [a,b,c]
How to you open a file?
f = open(‘filename’, ‘w’)
How do you write to a file?
f.write(‘text’)
How do you close a file?
f.close()
How do you read from a file?
text = f.read()
What is a set?
An unordered collection of immutable objects
How do you initailize a set?
Y = {‘h’, ‘a’, ‘m’}
How can you compute with decimal numbers?
import decimal
d = decimal.Decimal(‘3.1.415’)
How can you compute with fractions?
from fractions import Fraction
f = Fraction(2,3)
When are variables created?
When they are assigned.
How do you create a variable without assigning it?
You can’t.
How do you create comments in python?
comment…
How do you create random numbers?
import random
random.random()
How do you create random integers in a range?
import random
random.randint(1, 10)
How do you randomly select an item?
import random
random.choice([‘a’, ‘b’, ‘c’])
Where can you get advanced numeric methods?
NumPy