# examples of list comprehensions # # Matt Bishop, MHI 289I, Fall 2023 # # first, a for loop result = [ ] for i in range(9): result = result + [ i * i ] print("As in a for loop:", result) # now do it with list comprehension lcresult = [i * i for i in range(9)] print("As in list comprehension:", lcresult) # # now we only do this for even numbers up to 6, then 7, then 8 # # the way we have seen it in the past result = [ ] for i in range(9): if i % 2 == 0 or i == 7: result = result + [ i * i ] print("\nfor loop, even squares and 7 up to 8:", result) # and using list comprehension lcresult = [i * i for i in range(9) if i % 2 == 0 or i == 7] print("list comprehension, same thing:", lcresult)