tup = 'pi', ['py'], 'pie'
print(tup)
print(type(tup))
print(tup.__class__)
tuple() to convert from another sequence objectprint(
tuple("data")
)
print(tuple(["py", "thon"]))
[]. x = tup[0]
print(x)
... but their contents need not be.
try:
tup[1] = "python"
except:
print("Tuples are immutable")
tup[1].append("3.9")
print(tup)
+ ... ... or replicated using `*`.
tup2 = tup + tup
print(tup2)
tup3 = 3 * tup
print(tup3)
answer = 42, ("life", "universe", "everything")
a1, a2 = answer
print(a1)
print(a2)
answer = 42, ("life", "universe", "everything")
a1, (a2_1, a2_2, a2_3) = answer
print(a2_2)
a, b = 42, 3.14
b, a = a, b
print((a, b))
*_¶*_ to capture unwanted values ...... or `*name` to unpack into a list `name`.
num, (word1, *_) = answer
print(num)
print(word1)
print(_)
Tuples have few associated methods because they are immutable.
One useful method is, `count()`.
https://en.wikipedia.org/wiki/File:MagrittePipe.jpg
tuple("Leci n'est pas une pipe.").count('e')
[] or the list() function.my_list = (
["Leci n'est pas une pipe.",
(1, 2, 3, 5, 7, 11),
range(3)
])
for x in my_list:
print(type(x))
[]. list() function can be used to instantiate
iterators (or generators). print(my_list[1:2])
list(my_list[2])
.pop(), .remove()..append(), .insert(), .extend()print(my_list.pop(0)) # a position
my_list.remove(range(0, 3)) # takes a value
print(my_list)
my_list.append((17, 19, 23, 31, 37))
print(my_list)
.append(), .insert(), .extend()+. prime = list(my_list[0]) + list(my_list[1])
prime.insert(6, 13)
prime.extend([43, 47, 53])
prime
start:stop slicing.[start, stop): 0:n returns the first n elements. start defaults to 0, stop to the length of the list. print(prime[3:8])
prime[16:17] = [57, 59]
p = prime
(p[:3] == p[0:3]) & (p[3:len(p)] == p[3:]) & (p[len(p) - 1] == p[-1])
-1 reverses the list. print(prime[1::2])
print(prime[::-1])
print(prime[0:-1][::-1])
[expr for val in collection if condition]a = [x for x in my_list if isinstance(x, tuple)]
b = []
for x in my_list:
if isinstance(x, tuple):
b.append(x)
a == b
a, b, c, d, and e below into groups such that all
members of the group have the same value.x = list(range(10))
y = list(range(0, 10, 2)) #[0, 2, 4, 6, 8]
a = y[::-1]
b = x[1:4:2]
c = x[::2][::-1]
d = x[x[1]:y[2]:y[1]]
e = [i
for i in x
if 0 < i < 4 and i % 2 == 1]
flat1 = [
x
for tup in my_list
if isinstance(tup, tuple)
for x in tup]
flat2 = []
for tup in my_list:
if isinstance(tup, tuple):
for x in tup:
flat2.append(x)
flat1 == flat2
dict is used to associate
key-value pairs.
dictis likely the most important built-in Python data structure.--Wes McKinney
{} and a colon to
separate the key from the associated value ...dict() function. new_dict = {} # new_dict = dict()
res1 = {"mean": 4.2, "se": 0.21}
res2 = dict(mean=4.2, se=0.21)
res1 == res2 # same keys and values
dict objects use a hash table, key lookup happens in
constant time no matter how big the dict is. dict (to access, set, or update) using []. .get(). print(res["mean"])
res["lwr"] = res["mean"] - 1.96 * res["se"]
print(res.get("upr"))
.get() or .pop()
returns for a missing key.print(res.get("upr", "Not computed."))
x = {"a": 1, "b": 2, "c": 3}
for i in tuple("abcd"):
x.update({i: x.get(i, 0) + 1})
x
.keys(), .values(), .items().get() and .update().pop(), .copy()for k, v in d.items():
print('{' + '{0}: {1}'.format(k, v) + '}')
d = {i: np.sqrt(i) for i in range(10)}
sortedreversedenumeratezipenumerate() returns (index, value) pairs for sequences. x = [4, 9, 10, 29, 42, 17]
d = {}
for idx, val in enumerate(x):
d.update({val: idx})
d
sorted() returns a list with a sorted copy of a sequence object. reversed() returns a generator for iterating over items in a sequence
in reversed order. print(sorted(d))
list(reversed(d.values()))
zip() concatenates sequence objects element-wise into a "list" of tuples. list(zip(d.keys(), d.values()))
for k, v in zip(d.keys(), d.values()):
print('{' + '{0}: {1}'.format(k, v) + '}')
even = {x for x in range(0, 20) if x % 2 == 0}
div4 = {x for x in range(0, 20) if x % 4 == 0}
print(div4 < even) # subset
print(div4 & even) # intersection
print(div4 ^ even) # symmetric difference
dicts are a mutable set of key-value pairs, keys are unique
and are hashed making random look-ups efficient. wait for it ...
set logic.
enumeratezipsortedreversed