IntroductionThere is yet another type of loop. That loop is designed for iterating sets of data. That's right, lists. Unlike
forloops have a defined length based on the data set that they are iterating over.
forloops 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.
forloops have a slightly different structure than
whileloops do. They begin with the word
for, which is followed by the temporary variable being created for the loop. Then there is the keyword
inspecifying the set of data being used, followed by the data set itself and, ultimately, a colon.
For With RangeThere 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
forloop 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 * 2is passed to the
append()method on the newly created
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
forloop. 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
fortakes each distribution name from the list, temporarily assigns it to the
distrovariable, calls the
upper()method to capitalize and print it before calling the method again to append it on to the new
distros_capslist. In the end, it prints out both lists.
For With Multidimensional Lists
forloops have no problem iterating through multidimensional lists as well. Doing so involves nesting
forloops within one another. In a two dimensional list, the outer
forloop iterates through the lists within the multidimensional list, and the inner
forloop 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
forloop to iterate over the outer list and another to iterate over each inner list.
The last line of the inner
formight 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
numbersquared to the new list,
square_sets. Inside the square brackets is a call to
index(), which is taking in the current
numberand returning its position in the original list. That is done to ensure that each squared number is added to the right list within
ConclusionYou may find that
forloops are more useful more often than
whileloops. 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.
forloops 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
forloop that it uses to display just about everything on its pages. If you are still feeling uncertain about
forloops, 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
- Python Introduction and Installation Guide
- Python Files and the Interpreter
- Experimenting With Numbers and Text In Python
- Python Variables
- Working With Number Variables In Python
- Python String Basics
- Advanced Python Strings
- Python Comments
- Python Lists
- Python List Methods
- Python Multidimensional Lists
- Python Tuples
- Python Boolean Operators
- Python If Statements
- Python While Loops
- Python For Loops
- Python Dictionaries
- Python Advanced Dictionaries
- Python Functions