Professional Documents
Culture Documents
3 INTRO List
3 INTRO List
March 2, 2024
1 What is a List?
• A list is a collection of items in a “particular order”.
• You can make a list that includes the letters of the alphabet, the digits from 0 to 9.
• Square brackets ([ ]) indicate a list, and individual elements in list are separated by commas.
trek
cannondale
specialized
specialized
trek
1
1.3 Using Individual Values from a List
[ ]: message = f"My first bicycle was a {bicycles[0].title()}."
print(message)
[ ]: motorcycles = []
motorcycles.append("honda")
motorcycles.append("yamaha")
motorcycles.append("suzuki")
print(motorcycles)
2
2.2.2 [.insert()] Inserting Elements into a List
• You can add a new element at “any position” in your list by using the insert().
• You do this by specifying the index of the new element and the value of the new item.
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
3
2.3.3 [.pop()] Popping Items from Any Position in a List
Use pop() to remove an item from “any position” in a list by including the index of the item you
want to remove.
too_expensive = "ducati"
motorcycles.remove(too_expensive)
print(motorcycles)
print(f"A {too_expensive.title()} is too expensive for me.")
2.3.5 If you’re unsure whether to use the del statement or the pop() method,
• When you want to delete an item from a list and not use that item in any way, use the del
statement.
• If you want to use an item as you remove it, use the pop() method.
4
3 Organizing a List
3.1 [.sort()] Sorting a List “Permanently” with the “sort()” Method
• The sort() method changes the order of the list permanently.
• Never revert to the original order.
5
3.3 [.reverse()] Printing a List in Reverse Order
• To reverse the original order of a list, you can use the reverse() method.
• reverse() doesn’t sort backward alphabetically; it simply “reverses the order of the
list”.
• The reverse() method changes the order of a list permanently.
cars.reverse()
print(cars)
References:
• Eric Matthes - Python Crash Course-No Starch Press (2023)