Python: Data Structures 1

Main Python Data Structures Playlist

Contents

Arrays

Understand the basics of arrays in Python (using the array module and lists).

import array
# Create an integer array
arr = array.array('i', [1, 2, 3, 4])
print(arr)
print(arr[1])
arr.append(5)
print(arr)
arr.insert(2, 99)
print(arr)
arr.remove(99)
print(arr)
print('Length:', len(arr))
print('Slice:', arr[1:4])
# Iterate
for x in arr:
    print(x, end=' ')
print() 
# Arrays are type-restricted:
try:
    arr.append(3.14)
except TypeError as e:
    print('TypeError:', e)

Lists: Methods, Slicing, Comprehensions

Learn about Python lists, their methods, slicing, and list comprehensions.

# List creation
lst = [1, 2, 3]
empty = []
mixed = [1, 'a', 3.14, True]

# Methods
lst.append(4)
lst.extend([5, 6])
lst.insert(1, 99)
print(lst)
lst.remove(99)
print(lst)
print(lst.pop())
print(lst)
lst.reverse()
print(lst)
lst.sort()
print(lst)

# Slicing
nums = [0,1,2,3,4,5,6,7,8,9]
print(nums[2:7])
print(nums[:5])
print(nums[::2])
print(nums[::-1])

# List comprehension
squares = [x**2 for x in range(5)]
evens = [x for x in range(10) if x%2==0]
print(squares)
print(evens)

# Nested list comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix)

# Copying
copy1 = nums[:]
copy2 = list(nums)
print(copy1, copy2)

# Membership
print(3 in nums)
print(100 not in nums)

Tuples: Immutability, Packing/Unpacking

Explore tuples, their immutability, and how to pack/unpack values.

# Tuple creation
point = (2, 3)
single = (42,)
empty = ()

# Packing/unpacking
a, b = point
print(a, b)

# Immutability
try:
    point[0] = 10
except TypeError:
    print("Tuples are immutable!")

# Tuple methods
colors = ('red', 'green', 'blue', 'red')
print(colors.count('red'))
print(colors.index('green'))

# Tuple as dict key
mydict = { (1,2): 'a', (3,4): 'b' }
print(mydict[(1,2)])

# Nested tuples
nested = ((1,2), (3,4))
print(nested)

Sets: Operations, Set Comprehension

Learn about set operations and set comprehensions in Python.

# Set creation
A = {1, 2, 3}
B = set([2, 3, 4])
C = set()

# Operations
print(A | B)  # Union
print(A & B)  # Intersection
print(A - B)  # Difference
print(A ^ B)  # Symmetric difference
print(2 in A)

# Methods
A.add(10)
A.update([20, 30])
A.discard(2)
A.remove(3)
print(A)
A.clear()
print(A)

# Set comprehension
squares = {x**2 for x in range(5)}
print(squares)

# Frozen set
fs = frozenset([1,2,3])
print(fs)

# Set math
odds = {1,3,5,7}
evens = {2,4,6,8}
print(odds.isdisjoint(evens))
print(odds.issubset({1,3,5,7,9}))

Dictionaries: Methods, Comprehensions, defaultdict, OrderedDict

Master Python dictionaries, including methods, comprehensions, and special dict types.

# Dictionary creation
person = {"name": "Alice", "age": 25}
empty = {}
fromkeys = dict.fromkeys(['a','b','c'], 0)
print(person, empty, fromkeys)

# Methods
print(person.keys())
print(person.values())
print(person.items())
person['city'] = 'London'
print(person.get('city'))
person.update({'country': 'UK'})
print(person)
print(person.pop('age'))
print(person)

# Dict comprehension
squares = {x: x**2 for x in range(5)}
print(squares)

# Iteration
for k, v in person.items():
    print(k, v)

# defaultdict, OrderedDict
from collections import defaultdict, OrderedDict
d = defaultdict(int)
d["a"] += 1
d["b"] += 2
print(dict(d))

o = OrderedDict()
o["x"] = 1
o["y"] = 2
print(o)

# Nested dict
nested = {'outer': {'inner': 42}}
print(nested['outer']['inner'])