0% found this document useful (0 votes)
31 views36 pages

Lec 3

The document discusses tuples, sets, dictionaries, and strings in Python. It provides examples and explanations of these foundational data types, including how to define, access, iterate through and modify them. The document is a lecture on scientific Python covering these fundamental concepts.

Uploaded by

myturtle game
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views36 pages

Lec 3

The document discusses tuples, sets, dictionaries, and strings in Python. It provides examples and explanations of these foundational data types, including how to define, access, iterate through and modify them. The document is a lecture on scientific Python covering these fundamental concepts.

Uploaded by

myturtle game
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

CME 193: Introduction to Scientific Python

Lecture 3: Tuples, sets, dictionaries and strings

Sven Schmit

stanford.edu/~schmit/cme193

3: Tuples, sets, dictionaries and strings 3-1


Contents

Tuples

Dictionaries

Sets

Strings

Modules

Exercises

3: Tuples, sets, dictionaries and strings 3-2


Tuples

Seemingly similar to lists

>>> myTuple = (1, 2, 3)


>>> myTuple[1]
2
>>> myTuple[1:3]
(2, 3)

3: Tuples, sets, dictionaries and strings 3-3


Tuples are immutable

Unlike lists, we cannot change elements.

>>> myTuple = ([1, 2], [2, 3])


>>> myTuple[0] = [3,4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’tuple’ object does not
support item assignment
>>> myTuple[0][1] = 3
>>> myTuple
([1, 3], [2, 3])

3: Tuples, sets, dictionaries and strings 3-4


Packing and unpacking

t = 1, 2, 3
x, y, z = t

print t # (1, 2, 3)
print y # 2

3: Tuples, sets, dictionaries and strings 3-5


Functions with multiple return values

def simple_function():
return 0, 1, 2

print simple_function()
# (0, 1, 2)

3: Tuples, sets, dictionaries and strings 3-6


Contents

Tuples

Dictionaries

Sets

Strings

Modules

Exercises

3: Tuples, sets, dictionaries and strings 3-7


Dictionaries

A dictionary is a collection of key-value pairs.

An example: the keys are all words in the English language, and their
corresponding values are the meanings.

Lists + Dictionaries = $$$

3: Tuples, sets, dictionaries and strings 3-8


Defining a dictionary

>>> 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.

3: Tuples, sets, dictionaries and strings 3-9


No duplicate keys

Old value gets overwritten instead!

>>> d = {1: ’one’, 2: ’two’}


>>> d[1] = ’three’
>>> d
{1: ’three’, 2: ’two’}

3: Tuples, sets, dictionaries and strings 3-10


Access

We can access values by keys, but not the other way around

>>> d = {1: ’one’, 2: ’two’}


>>> print d[1]

Furthermore, we can check whether a key is in the dictionary by


key in dict

3: Tuples, sets, dictionaries and strings 3-11


Access

We can access values by keys, but not the other way around

>>> d = {1: ’one’, 2: ’two’}


>>> print d[1]

Furthermore, we can check whether a key is in the dictionary by


key in dict

3: Tuples, sets, dictionaries and strings 3-12


All keys, values or both

Use d.keys(), d.values() and d.items()

>>> d = {1: ’one’, 2: ’two’, 3: ’three’}


>>> d
{1: ’one’, 2: ’two’, 3: ’three’}
>>> d.keys()
[1, 2, 3]
>>> d.values()
[’one’, ’two’, ’three’]
>>> d.items()
[(1, ’one’), (2, ’two’), (3, ’three’)]

So how can you loop over dictionaries?

3: Tuples, sets, dictionaries and strings 3-13


Small exercise

Print all key-value pairs of a dictionary

>>> d = {1: ’one’, 2: ’two’, 3: ’three’}


>>> for key, value in d.items():
... print key, value
...
1 one
2 two
3 three

Instead of d.items(), you can use d.iteritems() as well. Better


performance for large dictionaries.

3: Tuples, sets, dictionaries and strings 3-14


Small exercise

Print all key-value pairs of a dictionary

>>> d = {1: ’one’, 2: ’two’, 3: ’three’}


>>> for key, value in d.items():
... print key, value
...
1 one
2 two
3 three

Instead of d.items(), you can use d.iteritems() as well. Better


performance for large dictionaries.

3: Tuples, sets, dictionaries and strings 3-15


Contents

Tuples

Dictionaries

Sets

Strings

Modules

Exercises

3: Tuples, sets, dictionaries and strings 3-16


Sets

Sets are an unordered collection of unique elements

>>> basket = [’apple’, ’orange’, ’apple’,


’pear’, ’orange’, ’banana’]
>>> fruit = set(basket) # create a set
>>> fruit
set([’orange’, ’pear’, ’apple’, ’banana’])
>>> ’orange’ in fruit # fast membership testing
True
>>> ’crabgrass’ in fruit
False

Implementation: like a dictionary only keys.


from: Python documentation

3: Tuples, sets, dictionaries and strings 3-17


Set comprehensions

>>> a = {x for x in ’abracadabra’ if x not in ’abc’}


>>> a
set([’r’, ’d’])

from: Python documentation

3: Tuples, sets, dictionaries and strings 3-18


Contents

Tuples

Dictionaries

Sets

Strings

Modules

Exercises

3: Tuples, sets, dictionaries and strings 3-19


Strings

Let’s quickly go over strings.

Strings hold a sequence of characters.

Strings are immutable

We can slice strings just like lists and tuples

Between quotes or triple quotes

3: Tuples, sets, dictionaries and strings 3-20


Everything can be turned into a string!

We can turn anything in Python into a string using str.

This includes dictionaries, lists, tuples, etc.

3: Tuples, sets, dictionaries and strings 3-21


String formatting

Special characters: \n, \t, \b, etc

Add variables: %s, %f, %e, %g, %d, or use format

fl = 0.23
wo = ’Hello’
inte = 12

print "s: {} \t f: {:0.1f} \n i: {}".format(wo, fl, inte)


# s: Hello f: 0.2
# i: 12

3: Tuples, sets, dictionaries and strings 3-22


Split

To split a string, for example, into seperate words, we can use split()

text = ’Hello, world!\n How are you?’


text.split()
# [’Hello,’, ’world!’, ’How’, ’are’, ’you?’]

3: Tuples, sets, dictionaries and strings 3-23


Split

What if we have a comma seperated file with numbers seperated by


commas?

numbers = ’1, 3, 2, 5’
numbers.split()
# [’1,’, ’3,’, ’2,’, ’5’]

numbers.split(’, ’)
# [’1’, ’3’, ’2’, ’5’]

[int(i) for i in numbers.split(’, ’)]


# [1, 3, 2, 5]

Use the optional argument in split() to use a custom seperator.

What to use for a tab seperated file?

3: Tuples, sets, dictionaries and strings 3-24


Split

What if we have a comma seperated file with numbers seperated by


commas?

numbers = ’1, 3, 2, 5’
numbers.split()
# [’1,’, ’3,’, ’2,’, ’5’]

numbers.split(’, ’)
# [’1’, ’3’, ’2’, ’5’]

[int(i) for i in numbers.split(’, ’)]


# [1, 3, 2, 5]

Use the optional argument in split() to use a custom seperator.

What to use for a tab seperated file?

3: Tuples, sets, dictionaries and strings 3-25


UPPER and lowercase

There are a bunch of useful string functions, such as .lower() and


.upper() that turn your string in lower- and uppercase.
Note: To quickly find all functions for a string, we can use dir

text = ’hello’
dir(text)

3: Tuples, sets, dictionaries and strings 3-26


join

Another handy function: join.


We can use join to create a string from a list.

words = [’hello’, ’world’]


’ ’.join(words)

’’.join(words)
# ’helloworld’

’ ’.join(words)
# ’hello world’

’, ’.join(words)
# ’hello, world’

3: Tuples, sets, dictionaries and strings 3-27


Contents

Tuples

Dictionaries

Sets

Strings

Modules

Exercises

3: Tuples, sets, dictionaries and strings 3-28


Importing a module

We can import a module by using import

E.g. import math

We can then access everything in math, for example the square root
function, by:

math.sqrt(2)

3: Tuples, sets, dictionaries and strings 3-29


Importing as

We can rename imported modules

E.g. import math as m

Now we can write m.sqrt(2)

3: Tuples, sets, dictionaries and strings 3-30


In case we only need some part of a module

We can import only what we need using the from ... import ...
syntax.

E.g. from math import sqrt

Now we can use sqrt(2) directly.

3: Tuples, sets, dictionaries and strings 3-31


Import all from module

To import all functions, we can use *:

E.g. from math import *

Again, we can use sqrt(2) directly.

Note that this is considered bad practice! It makes it hard to understand


where functions come from and what if several modules come with
functions with same name.

3: Tuples, sets, dictionaries and strings 3-32


Writing your own modules

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!’

print ’this is my first module’

import firstmodule
firstmodule.helloworld()

What do you notice?

3: Tuples, sets, dictionaries and strings 3-33


Only running code when main file

By default, Python executes all code in a module when we import it.


However, we can make code run only when the file is the main file:

def helloworld():
print ’hello, world!’

if __name__ == "__main__":
print ’this only prints when run directly’

Try it!

3: Tuples, sets, dictionaries and strings 3-34


Contents

Tuples

Dictionaries

Sets

Strings

Modules

Exercises

3: Tuples, sets, dictionaries and strings 3-35


Exercises

See course website for exercises for this week.

Get to know the person next to you and do them in pairs!

Let me know if you have any question

Class ends at 5:35pm.

3: Tuples, sets, dictionaries and strings 3-36

You might also like