Module 3 covers knowledge and skills for processing and manipulating data using:
fruits = ["apple", "banana", "cherry"]
numbers = list((1, 2, 3, 4))
mixed = [1, "hi", 3.14, [2, 4]]
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(fruits[1:3]) # ['banana', 'cherry']
numbers = [4, 2, 1]
numbers.append(7) # Add to end
numbers.insert(1, 5) # Insert at index 1
numbers.remove(2) # Remove first occurrence of 2
print(numbers.index(4)) # Find index of 4
more = numbers.copy() # Shallow copy
print(len(numbers), sorted(numbers), min(numbers), max(numbers))
# del instruction
# del numbers[0] # Remove item by index
squares = [x ** 2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]
matrix = [[1,2,3], [4,5,6], [7,8,9]]
print(matrix[1]) # [4, 5, 6]
print(matrix[1][2]) # 6
for fruit in fruits:
print(fruit)
if "banana" in fruits:
print("Found!")
cloned = fruits[:]
reverse() method or slicing.t1 = (1, 2, "hi")
t2 = tuple([3, 4, 5])
single = (7,) # Singleton tuple
coords = (2, 5, 8)
print(coords[0])
print(coords[1:])
a, b, c = (5, 6, 7) # Unpacking
t = (a, b, c) # Packing
person = {"name": "Tom", "age": 25}
empty = dict()
fromkeys = dict.fromkeys(["a", "b"], 0)
person["city"] = "London"
person["age"] = 26
removed = person.pop("name")
del person["age"]
print(person.keys())
print(person.values())
print(person.items())
person.clear()
for key in person:
print(key, person[key])
for k, v in person.items():
print(k, v)
if "city" in person:
print("City exists!")
data = {"A": {"score": 90}, "B": {"score": 85}}
print(data["A"]["score"])
s = "Python"
print(s[0], s[-1])
print(s[2:5])
t = "He said: "Hi!""
multi = """This is
multi-line"""
msg = " Hello, World! "
msg_lower = msg.lower()
msg_strip = msg.strip()
count_l = msg.count("l")
words = msg.split()
joined = "-".join(["a", "b", "c"])
found = msg.find("World")
name = "Jane"
age = 23
output = f"{name} is {age} years old." # f-strings
output2 = "{} is {} years old.".format(name, age)
| Concept | Syntax Example | Notes |
|---|---|---|
| List | mylist = [1, 2, 3] |
Mutable, ordered |
| Tuple | mytuple = (1, 2, 3) |
Immutable, ordered |
| Dictionary | mydict = {"a": 1, "b": 2} |
Key-value pairs, keys unique |
| String | s = "hello" |
Immutable, sequence of characters |
| Slicing | s[1:4], mylist[::-1] |
Get/reverse part(s) |
| Membership | 'a' in mylist, 'x' not in s |
Check existence |
| Comprehension | [x*2 for x in mylist] |
Compact loop/condition syntax |
| Nested | arr = [[1,2],[3,4]] |
List of lists (matrices) |
| Dict Methods | d.keys(), d.items(), d.get() |
Work with dict keys/values |
| Str Methods | s.strip(), s.find('a') |
Remove space, search character |