What is a list in Python?
Things we can do with lists.
What is a for loop?
Examples of loops.
Lists allow us to store multiple values together, in order. It's almost like having a row of cardboard boxes taped together: you can put something in each box and the items will stay in order!
Lists need to be created before you can use them. Here's how to create an empty list:
list1 = []
Now we can append new elements to the list:
list1.append(5)
list1.append(1)
list1.append(3)
list1.append(8)
list1.append(2)
print list1
What if we want to get a particular value held in a list? First, we need to know the index of the list element that holds the value we want. The index is like the street number of an address; the number increments by one for each building down the street. In the same way, counting from 0 to the element you want to access will give you the index.
Let's look at an example:
list2 = [7,5,6,23,15]
index = 2
print list2[index]
Index | 0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|---|
Value | 7 | 5 | 6 | 23 | 15 |
What other cool things you can do with lists?
Let's get the length:
size = len(list2)
print size
The code to print the last element in any list is below. Why do we need the -1?
print list2[len(list2)-1]
We can also sort a list:
list2.sort()
print list2
When do you use loops?
Have you ever had a situation where you have to do the same thing over and over again? Think about a jump rope. If you aren't into the fancy tricks you...
jump
jump
jump
jump
jump
Instead of writing jump 5 times, a loop makes it possible to write it once and assign it a number for how many times you want it written.
Let's jump 100 times:
for i in range(100):
print "jump"
What if you wanted to print out all the letters in the word Computer
for letter in "Computer":
print 'Current letter: ', letter
We can also access numbers in a range. Lets print numbers 0-99
for i in range(100):
print i
In this for loop we use range(). range() creates a set that can be looped through. When we write range(100) we are actually saying: [0,1,2,3,4,5,...,98,99]. In fact, this loop does exactly the same thing as the previous one:
list3 = range(100)
for num in list3:
print num
What if you wanted to add 0 - 19 to a list:
list4 = []
for i in range(20):
list4.append(i)
To print a list, we can we can use:
print list4
Or we can use:
for i in range(len(list4)):
print list4[i]
Loops can have multiple lines, too! Let's print some stars:
count = 16
for i in range(6):
count = count - i
print ('*' * count)