Lists and Loops
Let's go back to the first problem. Can we solve it with the Python we have learnt so far?
Problem: Let’s say I give you 5 cards. Each card has one number on it. Let’s say the numbers are 5,1,3,8,4. Find the largest number in the 5 cards.
I think we can do it like this
number1=5
number2=1
number3=3
number4=8
number5=4
largest=number1
if number2 > largest:
largest=number2
if number3 > largest:
largest=number3
if number4 > largest:
largest=number4
if number5 > largest:
largest=number5
print(largest)Great. This works. But what if the problem was to find the largest in 100 numbers. Or 1000 numbers. Or 10,000 numbers. Can you imagine how long the program will be and how long it will take to type it. We are missing something.
We are missing the vocabulary to store things as a group. We are missing the vocabulary to repeat things. If you look back, our English language solution to the problem was:
- Pick the first card.
- Pick the next card.
- If the new card is bigger then keep that in your hand and drop the older card. Basically keep the card with the larger number and drop the card with the smaller number.
- Do steps 2 and 3 until you run out of cards.
- The card in your hand is the largest card.
Step 4 is the important one. Look how we just said, do.... until. Lets see how we can do the same in Python.
First, lets look at how to group things. Python gives us lists. So instead of storing the invidual numbers in individual variables like number1, number2, number3 etc, we can store all the numbers in one list. We can define a list using [].
numbers=[5,1,3,8,4]Done. So much easier than defining one variable for each number. But how can we access the individual numbers? Easy, you can access them as numbers[0], numbers[1], numbers[2], numbers[3], numbers[4].
Did you notice something quirky? The first numbers was accessed as numbers[0]. The second was accessed as numbers[1] and so on. That means list element counting starts from 0. I know, I know. All your life you have counted things starting with 1. But in programming, for historical and other reasons, for list elements, the counting starts from 0. So if you want the 100th element in the list you can access it as numbers[99] if the list name is
Consider the list numbers above. If I do print(numbers[2]) it will print
print(numbers[5]) will print
Ok, now we just need the vocabulary to execute some statements repeatedly. And for that in Python, we have the 'for' statement.