Chapter 3: Lists Flashcards
create a simple list and print out the list as a whole
bicycles = [‘trek’, ‘Cannondale’, ‘redline’, ‘specialized’]
print(bicycles)
access every element in the list individually and print them out
bicycles = [‘trek’, ‘Cannondale’, ‘redline’, ‘specialized’]
print(bicycles[0])
use string methods on each of the elements of the list to change the case of the elements
print(bicycles[0].title())
access the last element in the list
print(bicycles[-1])
create an f-string in a variable to put an element of a list into the string. then print the string out
bicycles = [‘trek’, ‘Cannondale’, ‘redline’, ‘specialized’]
var = f”I really like the bikes made by {bicycles[0].title()}”)
print(var)
modify an element in a list
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
motorcycles[0] = ‘ducati’
print(motorcycles[0])
add an element to the list using .append()
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
motorcycles.append(‘ducati’)
print(motorcycles)
create another empty list and then add elements to it
var = [] var.append(' ') var.append(' ') var.append(' ') print(var)
use insert to add an element anywhere in the list
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
motorcyles.insert(2, ‘ducati’)
print(motorcycles)
use the delete function to remove an item from anywhere in the list
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
del motorcycles[0]
print(motorcycles)
use the pop method to move an element from a list to a variable
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
popped_cycle = motorcycles.pop()
print(popped_cycles)
add a popped variable to an f-string
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
popped_cycle = motorcycles.pop()
print(f”The last motorcycle I owned was a {popped_cycle.title()}”)
pop an item from anywhere in a list
motorcycles = ['honda', 'yamaha', 'suzuki'] popped_cycle = motorcycles.pop(0)
use remove to remove an element by its value
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
motorcycles.remove(‘honda’)
use .remove to remove an item from the list using a variable that contains that value
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’, ducati’]
too_expensive = ‘ducati’
motorcycles.remove(too_expensive)
print(motorcycles)