1 of 8

CSE 163

Tuples, Sets, and Dictionaries!

Oh My!�

Hunter Schafer

🎶 Listening to: Honne

💬 Before Class: How many holes does a straw have? Why?

2 of 8

This Time

  • List Comprehensions
  • Tuple
  • Sets
  • Dictionaries

Last Time

  • Lists
  • Files
  • Python Runtime
    • Scripts vs Jupyter
    • File Paths

2

3 of 8

Recap

Learned about 4 data structures so far!

  1. List� Has indices, this can be added/removed at any place
  2. Set � No duplicates, fast membership queries, no order
  3. Dictionary� Like a generic list that can have any value as keys� Keys are unique, values are not
  4. Tuple� Immutable list, used for multiple returns, can “unpack”

3

4 of 8

List Comprehensions

squares = [i ** 2 for i in range(1, 11) if i % 2 == 0]

squares = [

i ** 2

for i in range(1, 11)

if i % 2 == 0

]

4

1) What are you looping over?

2) [Optional] Skip if this is false

3) Expression with loop variable

4) Put it all in a list

5 of 8

Tuples

  • A tuple is a lot like a list, but is immutable! (can’t change it)
    • Uses parentheses as start/end

5

t = (1, "hello", 3.4)

print(t) # (1, 'hello', 3.4)

print(t[0]) # 1

t[1] = 'goodbye' # Error!

t = (1, "hello", 3.4)

print(t) # (1, 'hello', 3.4)

print(t[0]) # 1

t[1] = 'goodbye' # Error!

# You can "unpack" tuples to get their contents

a, b, c = t

print(b) # hello

6 of 8

Set

  • Data structure highly optimized for membership queries
    • if x in set” is very fast
  • Acts a lot like a list, BUT
    • Does not allow indexing operations
    • Does not allow duplicates�

Set Methods

6

set()

Makes an empty set

s.add(x)

Adds x to s

s.remove(x)

Removes x from s

s.clear()

Removes all values from s

7 of 8

Dictionary

  • Python has a data structure called a dictionary that allows us to use arbitrary data as indices (keys)

  • Demo notes
    • Keys are unique, values are not
    • Basically a “fancy” list, most syntax is familiar
  • Lesson 6 will show some more advanced usages of the dictionary

7

d = {}

d['a'] = 1

d['b'] = 2

print(d) # {'a': 1, 'b': 2}

8 of 8

Group Work:

Best Practices

When you first working with this group:

  • Introduce yourself!
  • If possible, angle one of your screens so that everyone can discuss together

Tips:

  • Starts with making sure everyone agrees to work on the same problem
  • Make sure everyone gets a chance to contribute!
  • Ask if everyone agrees and periodically ask each other questions!
  • Call TAs over for help if you need any!

8