tup = (4, 5, 6)
tup
tup = 4, 5, 6
tup
tuple([4, 0, 2])
tup = tuple('string')
tup
tup[0]
nested_tup = (4, 5, 6), (7, 8)
nested_tup
nested_tup[0]
nested_tup[1]
tup = tuple(['foo', [1, 2], True])
tup[2] = False
tup[1].append(3)
tup
(4, None, 'foo') + (6, 0) + ('bar',)
('foo', 'bar') * 4
tup = (4, 5, 6)
a, b, c = tup
b
tup = 4, 5, (6, 7)
a, b, (c, d) = tup
d
a, b = 1, 2
a
b
b, a = a, b
a
b
seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
for a, b, c in seq:
print(f'a={a}, b={b}, c={c}')
values = 1, 2, 3, 4, 5
a, b, *rest = values
a
b
rest
a, b, *_ = values
a = (1, 2, 2, 2, 3, 4, 2)
a.count(2)
a_list = [2, 3, 7, None]
tup = ("foo", "bar", "baz")
b_list = list(tup)
b_list
b_list[1] = "peekaboo"
b_list
gen = range(10)
gen
list(gen)
b_list.append("dwarf")
b_list
b_list.insert(1, "red")
b_list
b_list.pop(2)
b_list
b_list.append("foo")
b_list
b_list.remove("foo")
b_list
"dwarf" in b_list
"dwarf" not in b_list
[4, None, "foo"] + [7, 8, (2, 3)]
x = [4, None, "foo"]
x.extend([7, 8, (2, 3)])
x
a = [7, 2, 5, 1, 3]
a.sort()
a
b = ["saw", "small", "He", "foxes", "six"]
b.sort(key=len)
b
seq = [7, 2, 3, 7, 5, 6, 0, 1]
seq[1:5]
seq[3:5] = [6, 3]
seq
seq[:5]
seq[3:]
seq[-4:]
seq[-6:-2]
seq[::2]
seq[::-1]
empty_dict = {}
d1 = {"a": "some value", "b": [1, 2, 3, 4]}
d1
d1[7] = "an integer"
d1
d1["b"]
"b" in d1
d1[5] = "some value"
d1
d1["dummy"] = "another value"
d1
del d1[5]
d1
ret = d1.pop("dummy")
ret
d1
list(d1.keys())
list(d1.values())
list(d1.items())
d1.update({"b": "foo", "c": 12})
d1
tuples = zip(range(5), reversed(range(5)))
tuples
mapping = dict(tuples)
mapping
words = ["apple", "bat", "bar", "atom", "book"]
by_letter = {}
for word in words:
letter = word[0]
if letter not in by_letter:
by_letter[letter] = [word]
else:
by_letter[letter].append(word)
by_letter
by_letter = {}
for word in words:
letter = word[0]
by_letter.setdefault(letter, []).append(word)
by_letter
from collections import defaultdict
by_letter = defaultdict(list)
for word in words:
by_letter[word[0]].append(word)
hash("string")
hash((1, 2, (2, 3)))
hash((1, 2, [2, 3])) # fails because lists are mutable
d = {}
d[tuple([1, 2, 3])] = 5
d
set([2, 2, 2, 1, 3, 3])
{2, 2, 2, 1, 3, 3}
a = {1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7, 8}
a.union(b)
a | b
a.intersection(b)
a & b
c = a.copy()
c |= b
c
d = a.copy()
d &= b
d
my_data = [1, 2, 3, 4]
my_set = {tuple(my_data)}
my_set
a_set = {1, 2, 3, 4, 5}
{1, 2, 3}.issubset(a_set)
a_set.issuperset({1, 2, 3})
{1, 2, 3} == {3, 2, 1}
sorted([7, 1, 2, 6, 0, 3, 2])
sorted("horse race")
seq1 = ["foo", "bar", "baz"]
seq2 = ["one", "two", "three"]
zipped = zip(seq1, seq2)
list(zipped)
seq3 = [False, True]
list(zip(seq1, seq2, seq3))
for index, (a, b) in enumerate(zip(seq1, seq2)):
print(f"{index}: {a}, {b}")
list(reversed(range(10)))
strings = ["a", "as", "bat", "car", "dove", "python"]
[x.upper() for x in strings if len(x) > 2]
unique_lengths = {len(x) for x in strings}
unique_lengths
set(map(len, strings))
loc_mapping = {value: index for index, value in enumerate(strings)}
loc_mapping
all_data = [["John", "Emily", "Michael", "Mary", "Steven"],
["Maria", "Juan", "Javier", "Natalia", "Pilar"]]
names_of_interest = []
for names in all_data:
enough_as = [name for name in names if name.count("a") >= 2]
names_of_interest.extend(enough_as)
names_of_interest
result = [name for names in all_data for name in names
if name.count("a") >= 2]
result
some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
flattened = [x for tup in some_tuples for x in tup]
flattened
flattened = []
for tup in some_tuples:
for x in tup:
flattened.append(x)
[[x for x in tup] for tup in some_tuples]
def my_function(x, y):
return x + y
my_function(1, 2)
result = my_function(1, 2)
result
def function_without_return(x):
print(x)
result = function_without_return("hello!")
print(result)
def my_function2(x, y, z=1.5):
if z > 1:
return z * (x + y)
else:
return z / (x + y)
my_function2(5, 6, z=0.7)
my_function2(3.14, 7, 3.5)
my_function2(10, 20)
a = []
def func():
for i in range(5):
a.append(i)
func()
a
func()
a
a = None
def bind_a_variable():
global a
a = []
bind_a_variable()
print(a)
states = [" Alabama ", "Georgia!", "Georgia", "georgia", "FlOrIda",
"south carolina##", "West virginia?"]
import re
def clean_strings(strings):
result = []
for value in strings:
value = value.strip()
value = re.sub("[!#?]", "", value)
value = value.title()
result.append(value)
return result
clean_strings(states)
def remove_punctuation(value):
return re.sub("[!#?]", "", value)
clean_ops = [str.strip, remove_punctuation, str.title]
def clean_strings(strings, ops):
result = []
for value in strings:
for func in ops:
value = func(value)
result.append(value)
return result
clean_strings(states, clean_ops)
for x in map(remove_punctuation, states):
print(x)
def short_function(x):
return x * 2
equiv_anon = lambda x: x * 2
def apply_to_list(some_list, f):
return [f(x) for x in some_list]
ints = [4, 0, 1, 5, 6]
apply_to_list(ints, lambda x: x * 2)
strings = ["foo", "card", "bar", "aaaa", "abab"]
strings.sort(key=lambda x: len(set(x)))
strings
some_dict = {"a": 1, "b": 2, "c": 3}
for key in some_dict:
print(key)
dict_iterator = iter(some_dict)
dict_iterator
list(dict_iterator)
def squares(n=10):
print(f"Generating squares from 1 to {n ** 2}")
for i in range(1, n + 1):
yield i ** 2
gen = squares()
gen
for x in gen:
print(x, end=" ")
gen = (x ** 2 for x in range(100))
gen
sum(x ** 2 for x in range(100))
dict((i, i ** 2) for i in range(5))
import itertools
def first_letter(x):
return x[0]
names = ["Alan", "Adam", "Wes", "Will", "Albert", "Steven"]
for letter, names in itertools.groupby(names, first_letter):
print(letter, list(names)) # names is a generator
float("1.2345")
float("something")
def attempt_float(x):
try:
return float(x)
except:
return x
attempt_float("1.2345")
attempt_float("something")
float((1, 2))
def attempt_float(x):
try:
return float(x)
except ValueError:
return x
attempt_float((1, 2))
def attempt_float(x):
try:
return float(x)
except (TypeError, ValueError):
return x
path = "examples/segismundo.txt"
f = open(path, encoding="utf-8")
lines = [x.rstrip() for x in open(path, encoding="utf-8")]
lines
f.close()
with open(path, encoding="utf-8") as f:
lines = [x.rstrip() for x in f]
f1 = open(path)
f1.read(10)
f2 = open(path, mode="rb") # Binary mode
f2.read(10)
f1.tell()
f2.tell()
import sys
sys.getdefaultencoding()
f1.seek(3)
f1.read(1)
f1.tell()
f1.close()
f2.close()
path
with open("tmp.txt", mode="w") as handle:
handle.writelines(x for x in open(path) if len(x) > 1)
with open("tmp.txt") as f:
lines = f.readlines()
lines
import os
os.remove("tmp.txt")
with open(path) as f:
chars = f.read(10)
chars
len(chars)
with open(path, mode="rb") as f:
data = f.read(10)
data
data.decode("utf-8")
data[:4].decode("utf-8")
sink_path = "sink.txt"
with open(path) as source:
with open(sink_path, "x", encoding="iso-8859-1") as sink:
sink.write(source.read())
with open(sink_path, encoding="iso-8859-1") as f:
print(f.read(10))
os.remove(sink_path)
f = open(path, encoding='utf-8')
f.read(5)
f.seek(4)
f.read(1)
f.close()