Lists

Lists are kind of like arrays (if you do not know what an array is, we will go over it later on). A list could contain any given variable and however much your heart desires. You can also iterate a list over and over.

Here is an example of what a list looks like with Python:

x = []
x.append(1)
x.append(2)
x.append(3)
x.append(4)
x.append(5)

print(x[0]) # 1
print(x[1]) # 2
print(x[2]) # 3

for y in x:
   print(y) # prints out 1-5

Some import pieces that you may catch from the code above is that you see append(). That enables you to add to a list. You will also notice the brackets as well, those will allow us to select the specific values from the list.

Note: With programming, you will notice that the first value does not start with “1” but rather with “0.” If you would like to learn more as to why computers start with “0” instead of “1,” please check out this article: Why Do Computers Count From Zero.

When you try to access an index that does not exist, you would get an IndexError that would state “list index out of range.” To correct this, just make sure you are selecting from an actual range rather than an amount that does not exist.

x = [0,1,2,3,4,5,6,8,9]
print(x[11])

# The error message: 
# Traceback (most recent call last):
# File "<stdin>", line 2, in <module>
# print(mylist[10])
# IndexError: list index out of range

Exercise

Lets try an exercise to practice lists. For this exercise, lets try to add variables together (numbers and strings) by utilizing the append() method. You have to add 1-3 together for the numbers list and add the words “good” and “morning” to the strings variable.

For this exercise, you also have to fill in the variable last_name with the final name in the list (hint: use the brackets operator). Take a look at the final solution if you get stuck.

Exercise:

numbers = []
strings = []
names = ["Chuck", "Karen", "Michael", "Johnny", "Amy", "Joanne"]

# write your code here
last_name = None

print(numbers)
print(strings)
print("The final name on the names list is %s" % last_name)

Solution:

numbers = []
strings = []
names = ["Chuck", "Karen", "Michael", "Johnny", "Amy", "Joanne"]

# write your code here
numbers.append(1)
numbers.append(2)
numbers.append(3)

strings.append("good")
strings.append("morning")

last_name = names[5]

print(numbers)
print(strings)
print("The final name on the names list is %s" % last_name)

Output:

<script.py> output:
    [1, 2, 3]
    ['good', 'morning']
    The final name on the names list is Joanne

For more information

If you seek to learn more about Python, please visit Python’s official documentation.