Lists Flashcards
What is a list[]
example = [“dd”, “ff”]
Collection of items in a particular order
A list that holds “trek” “cannondale” “redline” “specialized”
print the array no(which holds these elements)
no = [“trek”, “cannondale” , “redline” , “specialized”]
print(no)
Print the 3rd item in a list
no = [“trek”, “cannondale” , “redline” , “specialized”]
print(no[2])
Individual values from a list
no = [“trek”, “cannondale” , “redline” , “specialized”]
Print the first item from the list, assign message to equal it, and print it
message = f”My first bike was a {no[0].title()} bike “
print(message)
Modify elements in a list
bikes = [‘nice’, ‘cool’, ‘wins’, ‘unck’]
Change the ‘wins’ to ‘loses’
bikes[2] = ‘loses’
print(bikes[2])
Adding(appending) elements to the end of a list
append() method for bikes = [‘nice’, ‘cool’, ‘wins’, ‘unck’]
bikes.append(‘more’)
print(bikes)
Add elements to an empty list
nicebikes = []
nicebikes. append(‘red’)
nicebikes. append(‘black’)
nicebikes. append( ‘white’)
insert elements into a list insert(index, element)
nicebikes = [‘red’, ‘black’, ‘white’]
Insert at the index postion 2 ‘blue’
Output: [‘red’, ‘black’, ‘blue’, ‘white’]
nicebikes.insert(2, ‘blue’)
print(nicebikes)
Remove an item from a list
del nicebikes[2]
Pop() method to remove an item
bikes = [‘nice’, ‘cool’, ‘wins’, ‘unck’]
- Pop ‘nice’ at index 0 defined as first_owned variable
- Print “I popped the nice bike”
first_owned = bikes.pop(0)
print(f”I popped the {first_owned.title() } bike “)
When should you use the del vs the pop() method?
-Delete is permeantenly get rid of the itme, pop to use the item as you remove it
Remove() method
-How can it be used?
bikes = [‘nice’, ‘cool’, ‘wins’, ‘unck’]
-Remove ‘wins’ from bikes with the remove() method
- Removes a string, interger or decimal value from a list
bikes. remove(‘wins’)
Permanenetly sort a list(alphabetically)
cars = [‘bad’ , ‘nope’ , ‘mo’]
cars.print()
print(cars)
temporarily sort a list
cars = [“how”, “very”, “cool”]
print(sorted(cars))
Reverse a list permanenetly
bikes = [‘nice’, ‘cool’, ‘wins’, ‘unck’]
bikes.reverse()
print(bikes)