Lec 3
Lec 3
Sven Schmit
stanford.edu/~schmit/cme193
Tuples
Dictionaries
Sets
Strings
Modules
Exercises
t = 1, 2, 3
x, y, z = t
print t # (1, 2, 3)
print y # 2
def simple_function():
return 0, 1, 2
print simple_function()
# (0, 1, 2)
Tuples
Dictionaries
Sets
Strings
Modules
Exercises
An example: the keys are all words in the English language, and their
corresponding values are the meanings.
>>> d = {}
>>> d[1] = "one"
>>> d[2] = "two"
>>> d
{1: ’one’, 2: ’two’}
>>> e = {1: ’one’, ’hello’: True}
>>> e
{1: ’one’, ’hello’: True}
Note how we can add more key-value pairs at any time. Also, only
condition on keys is that they are immutable.
We can access values by keys, but not the other way around
We can access values by keys, but not the other way around
Tuples
Dictionaries
Sets
Strings
Modules
Exercises
Tuples
Dictionaries
Sets
Strings
Modules
Exercises
fl = 0.23
wo = ’Hello’
inte = 12
To split a string, for example, into seperate words, we can use split()
numbers = ’1, 3, 2, 5’
numbers.split()
# [’1,’, ’3,’, ’2,’, ’5’]
numbers.split(’, ’)
# [’1’, ’3’, ’2’, ’5’]
numbers = ’1, 3, 2, 5’
numbers.split()
# [’1,’, ’3,’, ’2,’, ’5’]
numbers.split(’, ’)
# [’1’, ’3’, ’2’, ’5’]
text = ’hello’
dir(text)
’’.join(words)
# ’helloworld’
’ ’.join(words)
# ’hello world’
’, ’.join(words)
# ’hello, world’
Tuples
Dictionaries
Sets
Strings
Modules
Exercises
We can then access everything in math, for example the square root
function, by:
math.sqrt(2)
We can import only what we need using the from ... import ...
syntax.
It is perfectly fine to write and use your own modules. Simply import the
name of the file you want to use as module.
E.g.
def helloworld():
print ’hello, world!’
import firstmodule
firstmodule.helloworld()
def helloworld():
print ’hello, world!’
if __name__ == "__main__":
print ’this only prints when run directly’
Try it!
Tuples
Dictionaries
Sets
Strings
Modules
Exercises