Chapter 4: working with lists Flashcards
what does a for loop do?
a for loop pulls each individual value and associates it with the singular version of the list variable and then prints. this is repeated for each value in the list
writ a simple for loop for a list
magicians = [‘alice’, ‘david’, ‘carolina’]
for magician in magicians:
print(magician)
attach an f-string to a for loop
for magician in magicians:
print(f”{magician.title()}, that was a great trick!”)
write a for loop with multiple f-strings and then write code after the for loop to summarize the for loop
for magician in magicians:
print(f”\n{magician.title()}, that was a great trick!”)
print(f”I can’t wait to see your next trick,
{magician.title()}!”)
print(“\nThank you, everyone. That was a great magic show!”)
use range in a for loop to generate a series of numbers
think of what value the range will stop at before you print
for value in range(1, 5):
print(value)
what number does the for loop stop at when using range?
the one before the number listed, if you go 1 to 5 it will stop at 4
make a list in a variable from the range function
numbers = list(range(1, 6))
print(numbers)
make a list in a variable from the range function, but only print the even numbers
even_numbers = list(range(0, 30, 2))
print(even_numbers)
make an empty list, and put the first 10 square numbers into that list
squares = [] for value in range(1, 11): square = value ** 2 squares.append(square) or squares.append(value**2)
make a list of numbers, then print the sum,, min, and max of that list
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(sum(digits))
print(min(digits))
print(max(digits))
what is a list comprehension?
allows you to generate a list with just one line of code.
it combines a for loop and the creation of new elements into one line, and automatically append new elements
write a list comprehension using the creation of the first 10 squared numbers
squares = [value**2 for value in range(1, 11)]
print(squares)
Use a for loop to print the numbers from 1 to 20 inclusive from a list, both ways of making the list are fine.
numbers = list(range(1, 21))
for number in numbers:
print(number)
Make a list of the multiples of 3 from 3 to 30. Use a for loop to print the numbers in your list.
threes = list(range(3, 31, 3))
for number in threes:
print(number)
Use a list comprehension to generate a list of the first 10 cubes.
cubes = [number**3 for number in range(1,11)]
for cube in cubes:
print(cube)