Python For Loops

Introduction

There is yet another type of loop. That loop is designed for iterating sets of data. That’s right, lists. Unlike while loops, these for loops have a defined length based on the data set that they are iterating over.

Generally, for loops are used to access and modify each element in a list. To do this, they temporarily represent each element as a new variable used only within the loop.

for loops have a slightly different structure than while loops do. They begin with the word for, which is followed by the temporary variable being created for the loop. Then there is the keyword in specifying the set of data being used, followed by the data set itself and, ultimately, a colon.

For With Range

There is a method called range() that either takes a single number and behaves like a list of numbers going from zero until the number before the one specified or takes two numbers separated by a comma and acts like a slice starting at the first number and listing all numbers until the number before the last one.



Below is an example of a for loop that uses range() and multiplies each number in it by two.

for x in range(1, 11):
	print(x * 2)

It hasn’t changed anything. It only prints out the results. However, it can be used to create a new list.

times_two = []

for x in range(1, 11):
	times_two.append(x * 2)
	print(x * 2)

print(times_two)

Even though you didn’t start with a complete list, you can use range() to create one. To break it down a bit; range() outputs each number from one to ten. Then, each number is individually temporarily assigned to x. The result of x * 2 is passed to the append() method on the newly created times_two list.

For With Lists

range() is great, but it’s only really useful when working with numbers. Most of the time, you will be passing existing lists to a for loop. Take a look at this example that capitalizes the names of a list of Linux distributions.

# Create the list of distributions
linux_distros = ['Debian', 'Ubuntu', 'Mint', 'Fedora', 'CentOS', 'OpenSUSE', 'Slackware', 'Arch', 'Gentoo']

distros_caps = []

# loop through them, capitalize, insert into new 
for distro in linux_distros:
	print(distro.upper())
	distros_caps.append(distro.upper())

# print the original
print(linux_distros)
# print the new list
print(distros_caps)

This simple for takes each distribution name from the list, temporarily assigns it to the distro variable, calls the upper() method to capitalize and print it before calling the method again to append it on to the new distros_caps list. In the end, it prints out both lists.

For With Multidimensional Lists

for loops have no problem iterating through multidimensional lists as well. Doing so involves nesting for loops within one another. In a two dimensional list, the outer for loop iterates through the lists within the multidimensional list, and the inner for loop iterates through the elements of each list. It’s much easier to see through some actual running code.

# Create original list
number_sets = [[2, 4, 6], [3, 6, 9], [4, 8, 12]]

# Create empty list to copy into
square_sets = []

# Start outer for loop to iterate over inner lists
for number_set in number_sets:

	# Add a new empty list to the new list for each iteration
    square_sets.append([])
	
	# Start inner for loop to iterate over numbers and append them into the new list
    for number in number_set:
        print("The original number is %d, and the result is %d." % (number, number ** 2))
        square_sets[number_sets.index(number_set)].append(number ** 2)

print(square_sets)

The example above provides a better breakdown of exactly what it is doing when. The best way to think of it is that you need one for loop to iterate over the outer list and another to iterate over each inner list.

The last line of the inner for might be tripping some people up, but it’s not as complicated as it looks. All that it does is use append() to add the value of the current number squared to the new list, square_sets. Inside the square brackets is a call to index(), which is taking in the current number and returning its position in the original list. That is done to ensure that each squared number is added to the right list within square_sets.

Conclusion

You may find that for loops are more useful more often than while loops. They tend to be used very frequently. There is a reason why there were three guides on lists. They are important. They are constantly used. for loops go hand-in-hand with lists. They are absolutely the best way to get all of the information out of a list. One of the most crucial components of WordPress is its custom for loop that it uses to display just about everything on its pages. If you are still feeling uncertain about for loops, you need to go back and take another look at lists, come back to this guide, and run some examples. Experiment until you feel confident. There’s no point in going forward if you’re not.

Table of Contents

  1. Python Introduction and Installation Guide
  2. Python Files and the Interpreter
  3. Experimenting With Numbers and Text In Python
  4. Python Variables
  5. Working With Number Variables In Python
  6. Python String Basics
  7. Advanced Python Strings
  8. Python Comments
  9. Python Lists
  10. Python List Methods
  11. Python Multidimensional Lists
  12. Python Tuples
  13. Python Boolean Operators
  14. Python If Statements
  15. Python While Loops
  16. Python For Loops
  17. Python Dictionaries
  18. Python Advanced Dictionaries
  19. Python Functions


Comments and Discussions
Linux Forum