Programming in Python

BEES 2021

Agenda

  • Lists
  • List comprehensions

Lists

  • An ordered sequence of information, accessible by index
  • A list is denoted by sequence brackets "[ ]"
  • A list contains elements
    • Usually homogeneous
    • Can contain mixed types
  • List elements can be changed, so a list is mutable

List functions - review

Lists are mutable

  • Lists are mutable
  • Assigning to an element at an index changes the value

 

 

  • L is now [2, 5, 3], note this is the same object L
L = [2, 1, 3]
L[1] = 5

List mutability

Conversion and nesting

Aliasing vs. cloning

aliasing

0
 Advanced issues found
 
  • "hot" is an alias for "warm" - changing one changes the other
  • For example, here "append" has a side effect
a = 1
b = a
print(a)
print(b)

warm = ['red', 'yellow', 'orange']
hot = warm
hot.append('pink')
print(hot)
print(warm)

cloning

0
 Advanced issues found
 
  • Create a new list and copy every element using
cool = ['blue', 'green', 'gray']
chill = cool[:]
chill.append('black')
print(chill)
print(cool)
chill = cool[:]

lists of lists of lists of ...

0
 Advanced issues found
 
  • We can have nested lists
warm = ['yellow', 'orange']
hot = ['red']
brightcolors = []
brightcolors.append(warm)
brightcolors.append(hot)
print(brightcolors)
# [['yellow', 'orange'], ['red']]
hot.append('pink')
print(hot)
# ['red', 'pink']
print(brightcolors)
# [['yellow', 'orange'], ['red', 'pink']]

List comprehension

0
 Advanced issues found
 
  • A super useful mashup of a for loop, a list, and conditionals
x = [ "a", 1, 2, "list"]
# Makes a new list, l, containing only the strings in x
l = [ i for i in x if type(i) == str ] 

# The basic structure is:
# [ EXPRESSION1 for x in ITERABLE (optionally) if EXPRESSION2 ]

# it is equivalent to writing:
# l = []
# for x in ITERABLE:
#   if EXPRESSION2:
#       l.append(EXPRESSION1)

list comprehension Example

Lecture 7 challenge

Questions?