Course: CSCI 1250

Lists

  • Ordered and mutable
  • Can be heterogenous
  • Used for data that’s dynamic
  • Defined with square brackets
my_list = [1, 2, 3]
my_list[0] = 4
 
for item in my_list:
	print(item) # 4 -> 2 -> 3

List Comprehensions

  • Offers a shorter syntax when you want to create a list based on another list.
    • IE: creating a list of strings from a list of numbers
  • Can be used to map and filter lists.

Map

  • List comprehensions can be used to map lists, which convert some T to another value, U.
    • IE: list[str]list[int]
nums = [1, 2, 3]
stringified_nums = [str(n) for n in nums]
 
# Without list comprehension:
stringified_nums = []
for n in nums:
	stringified_nums.append(str(n))

Filter

  • List comprehensions can also be used to filter lists, which remove values from a list based on a predicate (a function that returns a boolean)
fruits = ["apple", "orange", "banana", "apple"]
apple_basket = [x for x in fruits if x == "apple"] # ["apple", "apple"]

Tuple

  • Ordered and immutable
  • Can be heterogenous
  • Used for fixed data/records
    • Defined with parentheses
coordinates = (69, 420)

Unpacking

  • Since lists and tuples are both iterators, they’re able to be unpacked.
  • Unpacking offers a way to assign variables from values within an iterator.
    • IE: assigning x and y variables from a coordinate
  • It can be used within loops.
    • IE: looping over a list of coordinates, you could unpack those values.
coordinates = [(1, 2), (3, 4)]
 
for x, y in coordinates:
	print(f"x: {x}, y: {y}") # x: 1, y: 2 -> x: 3, y: 4