Tuples

  • Tuples are like lists but
    • are immutable,
    • are created with ( ) instead of [ ],
    • elements are still accessed with [ ],
    • changing an element, like t[1]=55 gives an error.
In [7]:
t = (1.1, 2.2, 3.3)
t[1]
Out[7]:
2.2
  • For a tuple with just a single element:
    • Use this: t = (1.1,)
    • Not this: t = (1.1)
  • The trailing comma is needed, otherwise t is just 1.1, not a tuple holding 1.1 as the first element.
  • For multiple elements, a trailing comma is valid but not required: t = (1, 2, 3,)
    • Lists can also have trailing commas: L = [1, 2, 3,]

Tuple unpacking (mutiple assignment)

In [8]:
t = (1, 2.5 , -3)         # make a tuple

x, y, z   = t             # unpack the tuple "into" x, y, and z
x, y, z   = 1, 2.5, -3    # same thing
(x, y, z) = t             # same thing
(x, y, z) = (1, 2.5, -3)  # same thing

print(f"x = {x}")
print(f"y = {y}")
print(f"z = {z}")
x = 1
y = 2.5
z = -3

Note, we used this in returning more than one thing from a function

In [1]:
import numpy as np
def add_and_multiply(x, y):
    return x+y, x*y            # returning a tuple

s, p = add_and_multiply(3,4)   # unpack the tuple into s, p
t = add_and_multiply(3,4)      # t is a tuple


print(s, p)
print(t)
7 12
(7, 12)

Dictionaries

  • Dictionaries are like lists but
    • are created with { } instead of [ ],
    • use key:value pairs
    • elements are accessed with [key] instead of by [i] for some integer index i,
    • Below, we use strings as the keys, but they can be anything.
  • Click here for more information
In [11]:
mw = {
      "CO2":12.011+15.999*2,
      "H2O":1.0079*2+15.999,
      "O2" :15.999*2,
      "N2" :14.0067*2,
     }

print("mw of o2 is ", mw["O2"])

funcs = {np.sin:"what up sin?", np.log10:np.tanh}  # evil!

funcs[np.log10](22)
mw of o2 is  31.998
Out[11]:
1.0

Functions:

  • mw.keys()
  • mw.values()
  • mw.items()
  • len(mw)
In [14]:
for k in mw.keys():      
    print(k, mw[k])
CO2 44.009
H2O 18.0148
O2 31.998
N2 28.0134
In [16]:
for v in mw.values():
    print(v)
44.009
18.0148
31.998
28.0134
In [18]:
for k, v in mw.items():
    print(k,v)
    
mw.items()
CO2 44.009
H2O 18.0148
O2 31.998
N2 28.0134
Out[18]:
dict_items([('CO2', 44.009), ('H2O', 18.0148), ('O2', 31.998), ('N2', 28.0134)])

Check if present

In [20]:
if "H2" in mw:
    print("H2 is there")
else:
    print("H2 is not there")
    
H2 is not there

Add items

  • mw["new_key"] = newValue
In [10]:
print(mw)

mw["H2"] = 1.0079*2

print(mw)
{'CO2': 44.009, 'H2O': 18.0148, 'O2': 31.998, 'N2': 28.0134}
{'CO2': 44.009, 'H2O': 18.0148, 'O2': 31.998, 'N2': 28.0134, 'H2': 2.0158}

Delete items

  • del mw["some_key"]
  • mw.pop("some_key")
  • mw.popitem() deletes the last inserted item
In [11]:
print(mw)
mw.popitem()
print(mw)
{'CO2': 44.009, 'H2O': 18.0148, 'O2': 31.998, 'N2': 28.0134, 'H2': 2.0158}
{'CO2': 44.009, 'H2O': 18.0148, 'O2': 31.998, 'N2': 28.0134}