Lists: many values in order
One variable per ticket is fine for two tickets and hopeless for two hundred. A list holds any number of values, in order, under a single name.
tickets = [
"I was charged twice for one order",
"My parcel has not arrived",
"How do I change my password?",
]
print(len(tickets))
print(tickets[0])
print(tickets[-1])Square brackets make a list, with commas between the items. Writing one item per line is only for reading; Python does not mind either way.
tickets[0] is the first item, because positions count from 0. tickets[-1] counts from the end, so it is always the last item however long the list gets.
Adding and slicing
tickets.append("The parcel arrived but the box was crushed")
print(len(tickets))
print(tickets[:2])append adds an item to the end and changes the list itself. tickets[:2] is a slice: a new list of the items from the start up to, but not including, position 2.
A position that is not there
print(tickets[4])Four items sit at positions 0 to 3. Asking for position 4 is an IndexError. When a list's length can vary, check len before reaching for a position, or loop over it instead, which is the next lesson.
- Print
tickets[1]andtickets[-2]. Why is it the same ticket? - Print
tickets[1:]. - Use
tickets.insert(0, "Where is my invoice?")and print the whole list.
Little by little, you're building something great.