#!/usr/bin/env python # coding: utf-8 # In[1]: # In[2]: tup = (4, 5, 6) tup # In[3]: tup = 4, 5, 6 tup # In[4]: tuple([4, 0, 2]) tup = tuple('string') tup # In[5]: tup[0] # In[6]: nested_tup = (4, 5, 6), (7, 8) nested_tup nested_tup[0] nested_tup[1] # In[7]: tup = tuple(['foo', [1, 2], True]) tup[2] = False # In[8]: tup[1].append(3) tup # In[9]: (4, None, 'foo') + (6, 0) + ('bar',) # In[10]: ('foo', 'bar') * 4 # In[11]: tup = (4, 5, 6) a, b, c = tup b # In[12]: tup = 4, 5, (6, 7) a, b, (c, d) = tup d # In[13]: a, b = 1, 2 a b b, a = a, b a b # In[14]: seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] for a, b, c in seq: print(f'a={a}, b={b}, c={c}') # In[15]: values = 1, 2, 3, 4, 5 a, b, *rest = values a b rest # In[16]: a, b, *_ = values # In[17]: a = (1, 2, 2, 2, 3, 4, 2) a.count(2) # In[18]: a_list = [2, 3, 7, None] tup = ("foo", "bar", "baz") b_list = list(tup) b_list b_list[1] = "peekaboo" b_list # In[19]: gen = range(10) gen list(gen) # In[20]: b_list.append("dwarf") b_list # In[21]: b_list.insert(1, "red") b_list # In[22]: b_list.pop(2) b_list # In[23]: b_list.append("foo") b_list b_list.remove("foo") b_list # In[24]: "dwarf" in b_list # In[25]: "dwarf" not in b_list # In[26]: [4, None, "foo"] + [7, 8, (2, 3)] # In[27]: x = [4, None, "foo"] x.extend([7, 8, (2, 3)]) x # In[28]: a = [7, 2, 5, 1, 3] a.sort() a # In[29]: b = ["saw", "small", "He", "foxes", "six"] b.sort(key=len) b # In[30]: seq = [7, 2, 3, 7, 5, 6, 0, 1] seq[1:5] # In[31]: seq[3:5] = [6, 3] seq # In[32]: seq[:5] seq[3:] # In[33]: seq[-4:] seq[-6:-2] # In[34]: seq[::2] # In[35]: seq[::-1] # In[36]: empty_dict = {} d1 = {"a": "some value", "b": [1, 2, 3, 4]} d1 # In[37]: d1[7] = "an integer" d1 d1["b"] # In[38]: "b" in d1 # In[39]: d1[5] = "some value" d1 d1["dummy"] = "another value" d1 del d1[5] d1 ret = d1.pop("dummy") ret d1 # In[40]: list(d1.keys()) list(d1.values()) # In[41]: list(d1.items()) # In[42]: d1.update({"b": "foo", "c": 12}) d1 # In[43]: tuples = zip(range(5), reversed(range(5))) tuples mapping = dict(tuples) mapping # In[44]: 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 # In[45]: by_letter = {} for word in words: letter = word[0] by_letter.setdefault(letter, []).append(word) by_letter # In[46]: from collections import defaultdict by_letter = defaultdict(list) for word in words: by_letter[word[0]].append(word) # In[47]: hash("string") hash((1, 2, (2, 3))) hash((1, 2, [2, 3])) # fails because lists are mutable # In[48]: d = {} d[tuple([1, 2, 3])] = 5 d # In[49]: set([2, 2, 2, 1, 3, 3]) {2, 2, 2, 1, 3, 3} # In[50]: a = {1, 2, 3, 4, 5} b = {3, 4, 5, 6, 7, 8} # In[51]: a.union(b) a | b # In[52]: a.intersection(b) a & b # In[53]: c = a.copy() c |= b c d = a.copy() d &= b d # In[54]: my_data = [1, 2, 3, 4] my_set = {tuple(my_data)} my_set # In[55]: a_set = {1, 2, 3, 4, 5} {1, 2, 3}.issubset(a_set) a_set.issuperset({1, 2, 3}) # In[56]: {1, 2, 3} == {3, 2, 1} # In[57]: sorted([7, 1, 2, 6, 0, 3, 2]) sorted("horse race") # In[58]: seq1 = ["foo", "bar", "baz"] seq2 = ["one", "two", "three"] zipped = zip(seq1, seq2) list(zipped) # In[59]: seq3 = [False, True] list(zip(seq1, seq2, seq3)) # In[60]: for index, (a, b) in enumerate(zip(seq1, seq2)): print(f"{index}: {a}, {b}") # In[61]: list(reversed(range(10))) # In[62]: strings = ["a", "as", "bat", "car", "dove", "python"] [x.upper() for x in strings if len(x) > 2] # In[63]: unique_lengths = {len(x) for x in strings} unique_lengths # In[64]: set(map(len, strings)) # In[65]: loc_mapping = {value: index for index, value in enumerate(strings)} loc_mapping # In[66]: all_data = [["John", "Emily", "Michael", "Mary", "Steven"], ["Maria", "Juan", "Javier", "Natalia", "Pilar"]] # In[67]: 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 # In[68]: result = [name for names in all_data for name in names if name.count("a") >= 2] result # In[69]: some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] flattened = [x for tup in some_tuples for x in tup] flattened # In[70]: flattened = [] for tup in some_tuples: for x in tup: flattened.append(x) # In[71]: [[x for x in tup] for tup in some_tuples] # In[72]: def my_function(x, y): return x + y # In[73]: my_function(1, 2) result = my_function(1, 2) result # In[74]: def function_without_return(x): print(x) result = function_without_return("hello!") print(result) # In[75]: def my_function2(x, y, z=1.5): if z > 1: return z * (x + y) else: return z / (x + y) # In[76]: my_function2(5, 6, z=0.7) my_function2(3.14, 7, 3.5) my_function2(10, 20) # In[77]: a = [] def func(): for i in range(5): a.append(i) # In[78]: func() a func() a # In[79]: a = None def bind_a_variable(): global a a = [] bind_a_variable() print(a) # In[80]: states = [" Alabama ", "Georgia!", "Georgia", "georgia", "FlOrIda", "south carolina##", "West virginia?"] # In[81]: 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 # In[82]: clean_strings(states) # In[83]: 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 # In[84]: clean_strings(states, clean_ops) # In[85]: for x in map(remove_punctuation, states): print(x) # In[86]: def short_function(x): return x * 2 equiv_anon = lambda x: x * 2 # In[87]: 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) # In[88]: strings = ["foo", "card", "bar", "aaaa", "abab"] # In[89]: strings.sort(key=lambda x: len(set(x))) strings # In[90]: some_dict = {"a": 1, "b": 2, "c": 3} for key in some_dict: print(key) # In[91]: dict_iterator = iter(some_dict) dict_iterator # In[92]: list(dict_iterator) # In[93]: def squares(n=10): print(f"Generating squares from 1 to {n ** 2}") for i in range(1, n + 1): yield i ** 2 # In[94]: gen = squares() gen # In[95]: for x in gen: print(x, end=" ") # In[96]: gen = (x ** 2 for x in range(100)) gen # In[97]: sum(x ** 2 for x in range(100)) dict((i, i ** 2) for i in range(5)) # In[98]: 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 # In[99]: float("1.2345") float("something") # In[100]: def attempt_float(x): try: return float(x) except: return x # In[101]: attempt_float("1.2345") attempt_float("something") # In[102]: float((1, 2)) # In[103]: def attempt_float(x): try: return float(x) except ValueError: return x # In[104]: attempt_float((1, 2)) # In[105]: def attempt_float(x): try: return float(x) except (TypeError, ValueError): return x # In[106]: path = "examples/segismundo.txt" f = open(path, encoding="utf-8") # In[107]: lines = [x.rstrip() for x in open(path, encoding="utf-8")] lines # In[108]: f.close() # In[109]: with open(path, encoding="utf-8") as f: lines = [x.rstrip() for x in f] # In[110]: f1 = open(path) f1.read(10) f2 = open(path, mode="rb") # Binary mode f2.read(10) # In[111]: f1.tell() f2.tell() # In[112]: import sys sys.getdefaultencoding() # In[113]: f1.seek(3) f1.read(1) f1.tell() # In[114]: f1.close() f2.close() # In[115]: 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 # In[116]: import os os.remove("tmp.txt") # In[117]: with open(path) as f: chars = f.read(10) chars len(chars) # In[118]: with open(path, mode="rb") as f: data = f.read(10) data # In[119]: data.decode("utf-8") data[:4].decode("utf-8") # In[120]: 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)) # In[121]: os.remove(sink_path) # In[122]: f = open(path, encoding='utf-8') f.read(5) f.seek(4) f.read(1) f.close() # In[123]: