Looping over lists in Python
A common use case when programming is the need to apply the same kind of operation to a list of variables. Think, for example, of a script that needs to connect to a few routers. For this to work, the script will need to know the Internet Protocol (IP) addresses of said routers and then perform the same set of commands on them. Instead of copying and pasting the same code multiple times and just changing the router IP, we can create a list of our IPs and then execute the commands.
In this recipe, you will see how to create a list of IP addresses and print them out using a for
loop. We will reuse the same concept in the next chapter to actually connect to the device and issue configuration commands.
Getting ready
Open your code editor and start by creating a file called loops.py
. Next, navigate your terminal to the same directory in which you just created the loops.py
file.
How to do it…
In this recipe, we will create IP version 4...