November 2, 2020

# Python - Kontainer

Python menyertakan beberapa jenis kontainer bawaan: list, dictionary, set, dan tuple.

List

List adalah padanan Python untuk array, tetapi ukurannya bisa elastik (dapat diubah) dan elemennya bisa terdiri dari berbagai tipe.

``````xs = [3, 1, 2]    # Create a list

print(xs, xs[2])  # Prints "[3, 1, 2] 2"
print(xs[-1])     # Negative indices count from the end of the list; prints "2"

xs[2] = 'foo'     # Lists can contain elements of different types
print(xs)         # Prints "[3, 1, 'foo']"

xs.append('bar')  # Add a new element to the end of the list
print(xs)         # Prints

x = xs.pop()      # Remove and return the last element of the list
print(x, xs)      # Prints "bar [3, 1, 'foo']"
``````

List - Slicing

Selain mengakses elemen list satu per satu, Python menyediakan sintaks ringkas untuk mengakses sublist; prosedur ini dikenal sebagai slicing.

``````nums = list(range(5)) # range is a built-in function that creates a list of integers
print(nums)           # Prints "[0, 1, 2, 3, 4]"

print(nums[2:4])    # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])     # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])     # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])      # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print(nums[:-1])    # Slice indices can be negative; prints ["0, 1, 2, 3]"

nums[2:4] = [8, 9]  # Assign a new sublist to a slice
print(nums)         # Prints "[0, 1, 8, 9, 4]"
``````

List - Looping

Kita dapat melakukan looping untuk setiap elemen dalam list.

Jika ingin mengakses indeks setiap elemen di dalam loop, gunakan fungsi bawaan enumerate.

``````animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)

# Prints "cat", "dog", "monkey", each on its own line.

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))

# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
``````

List - List Comprehension

Dalam pemrograman, seringkali kita ingin mentransformasi data i.e. mengubah satu jenis data menjadi yang lain. Hal ini dapat dilakukan dengan list comprehension (LC).

LC juga dapat bersifat kondisional, melakukan transformasi jika memenuhi kriteria tertentu.

``````nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
squares.append(x ** 2)
print(squares)   # Prints [0, 1, 4, 9, 16]

nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares)   # Prints [0, 1, 4, 9, 16]

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)  # Prints "[0, 4, 16]"
``````

Dictionary

Dictionary (dict) menyimpan pasangan (key, value), mirip dengan Map dalam bahasa pemrograman Java atau objek di Javascript.

Dictionary - Looping

Looping dict bisa dilakukan dalam bentuk seperti halnya looping list, khususnya untuk iterasi terhadap key. Jika kita ingin melakukan iterasi terhadap key dan value sekaligus, dapat menggunakan metode `items()`.

``````d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
print(d['cat'])       # Get an entry from a dictionary; prints "cute"
print('cat' in d)     # Check if a dictionary has a given key; prints "True"

d['fish'] = 'wet'    # Set an entry in a dictionary
print(d['fish'])     # Prints "wet"

# print(d['monkey'])  # KeyError: 'monkey' not a key of d
print(d.get('monkey', 'N/A'))  # Get an element with a default; prints "N/A"
print(d.get('fish', 'N/A'))    # Get an element with a default; prints "wet"

del(d['fish'])        # Remove an element from a dictionary
print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"
``````
``````d = {'chicken': 2, 'cat': 4, 'spider': 8}

for animal in d:
legs = d[animal]
print('A %s has %d legs' % (animal, legs))

# Prints "A chicken has 2 legs", "A spider has 8 legs", "A cat has 4 legs"
``````
``````d = {'chicken': 2, 'cat': 4, 'spider': 8}

for animal, legs in d.items():
print('A %s has %d legs' % (animal, legs))

# Prints "A chicken has 2 legs", "A spider has 8 legs", "A cat has 4 legs"
``````

Dictionary - Dictionary Comprehension

Pada prinsipnya mirip dengan list comprehension, hanya dengan format key:value. Dictionary comprehension memungkinkan kita untuk menkonstruksi dict dengan mudah.

``````nums = [0, 1, 2, 3, 4]

even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}

print(even_num_to_square)  # Prints "{0: 0, 2: 4, 4: 16}"
``````

Set

Sebuah set atau himpunan adalah kumpulan elemen berbeda yang tidak terurut.

``````animals = {'cat', 'dog'}
print('cat') in animals   # Check if an element is in a set; prints "True"
print('fish') in animals  # prints "False"

print('fish' in animals) # Prints "True"
print(len(animals))      # Number of elements in a set; prints "3"

print(len(animals))      # Prints "3"

animals.remove('cat')    # Remove an element from a set
print(len(animals))      # Prints "2"
``````

Set - Looping

Proses looping untuk set juga hampir sama dengan list. Hanya, karena set tidak terurut, kita tidak bisa menentukan urutan elemen secara eksak.

Set - Set Comprehension

Sebagaimana list dan dict, set juga dapat dikonstruksi menggunakan set comprehension dengan prosedur yang sama.

``````animals = {'cat', 'dog', 'fish'}

for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))

# Prints "#1: fish", "#2: dog", "#3: cat"
``````
``````from math import sqrt

nums = {int(sqrt(x)) for x in range(30)}

print(nums)  # Prints "set([0, 1, 2, 3, 4, 5])"
``````

Tuple

Tuple adalah kontainer seperti list, tetapi dengan elemen data terurut yang immutable (tidak dapat diubah). Tuple dalam banyak hal mirip dengan list.

Salah satu perbedaan terpenting adalah bahwa tuple dapat digunakan: (1) sebagai key dalam dict dan (2) sebagai elemen set. Untuk kedua hal ini, list tidak bisa.

``````d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
t = (5, 6)       # Create a tuple

print(type(t))    # Prints "<type 'tuple'>"
print(d[t])       # Prints "5"
print(d[(1, 2)])  # Prints "1"
``````

#### Cheatsheet List (@gto76)

``````<list> = <list>[from_inclusive : to_exclusive : ±step_size]
``````
``````<list>.append(<el>)            # Or: <list> += [<el>]
<list>.extend(<collection>)    # Or: <list> += <collection>
``````
``````<list>.sort()
<list>.reverse()
<list> = sorted(<collection>)
<iter> = reversed(<list>)
``````
``````sum_of_elements  = sum(<collection>)
elementwise_sum  = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both   = sorted(<collection>, key=lambda el: (el[1], el[0]))
flatter_list     = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, el: out * el, <collection>)
list_of_chars    = list(<str>)
``````
• Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
``````<int> = <list>.count(<el>)     # Returns number of occurrences. Also works on strings.
index = <list>.index(<el>)     # Returns index of first occurrence or raises ValueError.
<list>.insert(index, <el>)     # Inserts item at index and moves the rest to the right.
<el> = <list>.pop([index])     # Removes and returns item at index or from the end.
<list>.remove(<el>)            # Removes first occurrence of item or raises ValueError.
<list>.clear()                 # Removes all items. Also works on dictionary and set.
``````

#### Cheatsheet Dictionary (@gto76)

``````<view> = <dict>.keys()                          # Coll. of keys that reflects changes.
<view> = <dict>.values()                        # Coll. of values that reflects changes.
<view> = <dict>.items()                         # Coll. of key-value tuples that reflects chgs.
``````
``````value  = <dict>.get(key, default=None)          # Returns default if key is missing.
value  = <dict>.setdefault(key, default=None)   # Returns and writes default if key is missing.
<dict> = collections.defaultdict(<type>)        # Creates a dict with default value of type.
<dict> = collections.defaultdict(lambda: 1)     # Creates a dict with default value 1.
``````
``````<dict> = dict(<collection>)                     # Creates a dict from coll. of key-value pairs.
<dict> = dict(zip(keys, values))                # Creates a dict from two collections.
<dict> = dict.fromkeys(keys [, value])          # Creates a dict from collection of keys.
``````
``````<dict>.update(<dict>)                           # Adds items. Replaces ones with matching keys.
value = <dict>.pop(key)                         # Removes item or raises KeyError.
{k for k, v in <dict>.items() if v == value}    # Returns set of keys that point to the value.
{k: v for k, v in <dict>.items() if k in keys}  # Returns a dictionary, filtered by keys.
``````

Counter

``````>>> from collections import Counter
>>> colors = ['blue', 'blue', 'blue', 'red', 'red']
>>> counter = Counter(colors)
>>> counter['yellow'] += 1
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
``````

#### Cheatsheet Set (@gto76)

``````<set> = set()
``````
``````<set>.add(<el>)                                 # Or: <set> |= {<el>}
<set>.update(<collection>)                      # Or: <set> |= <set>
``````
``````<set>  = <set>.union(<coll.>)                   # Or: <set> | <set>
<set>  = <set>.intersection(<coll.>)            # Or: <set> & <set>
<set>  = <set>.difference(<coll.>)              # Or: <set> - <set>
<set>  = <set>.symmetric_difference(<coll.>)    # Or: <set> ^ <set>
<bool> = <set>.issubset(<coll.>)                # Or: <set> <= <set>
<bool> = <set>.issuperset(<coll.>)              # Or: <set> >= <set>
``````
``````<el> = <set>.pop()                              # Raises KeyError if empty.
<set>.remove(<el>)                              # Raises KeyError if missing.
<set>.discard(<el>)                             # Doesn't raise an error.
``````

Frozen Set

• Is immutable and hashable.
• That means it can be used as a key in a dictionary or as an element in a set.
``````<frozenset> = frozenset(<collection>)
``````

#### Cheatsheet Tuple (@gto76)

Tuple is an immutable and hashable list.

``````<tuple> = ()
<tuple> = (<el>, )
<tuple> = (<el_1>, <el_2> [, ...])
``````

Named Tuple Tuple’s subclass with named elements.

``````>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
>>> p._fields  # Or: Point._fields
('x', 'y')
``````