Programming with Python: Lists and For-Loops


Hello again! Earlier, we learned about the basics of while-loops and if-statements. In this post, we’ll be learning about lists and for-loops, and how to combine them with our knowledge of while-loops and if-statements.

What are Lists?

A list in Python is one of several data types, called containers, that can hold more than one value. Of the several different types of containers, lists are the simplest. An example of how to declare a list would be:

days_of_the_week = ['Sunday','Monday','Tuesday','Wednesday', 
                    'Thursday','Friday','Saturday']

That’s it! Just declare a variable, enclose your list in brackets, and use commas to separate the individual items. An example of how to use a list in a program would be:

day_chosen = int(input("Which day of the week do you want?"))
days_of_the_week = ['Sunday','Monday','Tuesday','Wednesday',
                    'Thursday','Friday','Saturday']

if day_chosen >= 1 and day_chosen <= 7:   #if they chose a valid
                                           number
    print("The day you chose is : ", days_of_the_week[day_chosen - 1])      #Print the day chosen

This program lets the user choose a day of the week (with 1 being Sunday, 2 being Monday and so on), and the program then accesses the list of days and chooses the corresponding day. I’ve highlighted two pieces of code that may need explaining.

The “and” and “or” operators

The first is the and operator, which we have not used before now. The “and” operator allows you to have multiple conditions for an if-statement. If you use the “and” operator, then both of the conditions must be true. In the above code, the number must be both greater than or equal to 1 and less than or equal to 7.

While we are on the topic, I should also mention the or operator. The “or” operator also allows you to have multiple conditions, but lets the code execute if one of the conditions are true. To give a simple example, consider the following:

1 is greater than 0 and even : False
4 is less than 10 and even : True
3 is less than 4 or odd : True
3 is less than 4 or even : False

The above isn’t Python code, but I wanted to put it into words to make it clear. With and, both conditions have to be true, but with or, only one has to be true.

With both of these operators, it is very important that you declare which variable you are comparing each time, like so:

my_var = 'b'
if my_var == 'a' or my_var == 'b':

this will result in the expected outcome (true). However, if you type the code like this:

my_var = 'b'
if my_var == 'a' or 'b':

then you’ll be confused when Python tells you the answer is “False”. Basically, if you forget and write it the second way, the boolean operators return one of the operands. So instead of returning true or false, if will return ‘a’ or ‘b’, which isn’t what we want. There’s a reason for this, but it’s kinda complicated and there’s no reason to explain it yet. Just don’t do it 🙂

Important note on iterating through loops

The next important thing to mention; you may be wondering why we subtracted 1 from the “day_chosen” variable in the highlighted code a few paragraphs above. That’s because in Python (and most programming languages), counting for things likes lists start at zero. So that means, in our list of days, Sunday is the 0th day, at least to Python. If we had a list of months, January would be the 0th month, and so on. This is important to know, if you ever get a “list index out of range” error in the console, you’re probably forgetting this principle. Here’s a graphic that shows an example of a list:

Example of a list in Python

A list of the first ten prime numbers

 

How to Iterate Through a List : For-Loops

We already know about while-loops, but if we have a list and know when we want the loop to stop it is much better to use a for-loop. With a for-loop, we are able to specify exactly where the loop begins and where the loop ends. Let’s say I want to go through a list of numbers and determine which ones are odd or even:

list_of_nums = [7, 2, 8, 23, 18, 134, 5000, 111, 34, 99]

for count in list_of_nums:
    if count % 2 == 0:
        print(count, " is even. ")
    else:
        print(count, " is odd. ")

You can also make a for-loop go through a certain range of numbers with the range function:

for count in range(1,11):
    print(count)

Or alternatively:

from_one_to_ten = [1,2,3,4,5,6,7,8,9,10]

for count in one_to_ten:
    print(count)

As you may have guessed, we can technically do any of these things with while-loops, but using a for-loop is usually easier to plan out and understand. It also knocks out the possibility of starting an infinite loop.

I’ll also point out that, if you have any experience in another programming language like C++ or Java, you may find it weird that we declare a variable (count) in the for-loop statement and don’t assign a value. Python is smart enough to know that if you use a for-loop with a list that the variable should start as 0. If you needed it to start as something else you would’ve defined it as such earlier anyway. Another subtle difference for those whom it may concern is that, unlike other languages, the variable in a if-statement or loop does not go away after you exit the loop. If we wanted to print count 20 lines further down the code we could.

And that’s the basics of for-loops and lists. In the next post, we’ll go into more detail with lists and how to access specific parts of a list, as well as how to create a list from user input. In doing so, we’ll also give ourselves some much needed practice with loops and if-statements.

Thank you for taking the time to read my blog, and as always if you have any questions or concerns please leave a comment below or email me at talkingtoyourcomputer@gmail.com

Hey there! I'm a college student looking to learn about programming. I have a blog where I write about what I know and learn, and give in-depth posts on learning programming languages.

Tagged with: , ,
Posted in Programming, Python
One comment on “Programming with Python: Lists and For-Loops
  1. […] Programming with Python: Lists and For-Loops July 21, 2014 […]

    Like

Have any questions, thoughts, or concerns? Leave a comment!

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 16 other subscribers
Follow Talking to Your Computer on WordPress.com
Contact Me At:
talkingtoyourcomputer@gmail.com