Home Artificial Intelligence Simplify Your Code with the Python For Loop

Simplify Your Code with the Python For Loop

1
Simplify Your Code with the Python For Loop

Learn the best way to use Python’s powerful looping construct to make your code more efficient.

Photo by Nick Fewings on Unsplash

The Python for-loop is used to iterate dynamically over a sequence of objects and to perform calculations with them, for instance. It mechanically deals with different lengths of the objects and may thus save work in programming.

Within the Python programming language, for-loops are used mainly for working with Python Lists, as a way to change the objects inside the list or to have the option to make use of them for one more calculation. The advantage of using the loop is that it just isn’t essential to know the length of the list or the person indices of objects.

The for-loop in Python differs massively from those known in other programming languages. In these, it is barely used as a substitute for the while loop, i.e. to perform a calculation so long as a condition is met. In Python, however, it is meant specifically for working with objects and particularly lists.

The structure of a for-loop is all the time relatively similar and begins with the word “for”. That is followed by the variable name, whose value changes with each run. In our case, we call this “variable” and run through the item “object”. In each pass, the variable takes the worth of the element that’s currently within the queue. The word “in” separates the variable name and the name of the item being traversed:

The road ends with a colon and the following line then starts with an indentation. Each line that’s indented after the for statement is executed in a single pass. Here, calculations will be executed or, as in our example, simply the weather of the list will be output:

In the event you don’t wish to use the for-loop for iteration over a concrete object, but only in order that a command is executed multiple times, then the range() function is used. It’s written as an alternative of the item name and defines a spread of values that’s iterated through. There are three specifications for this function: range(start, stop, step). So you may specify at which number the function should start, that is by default 0. As well as, you may specify at which value the function should stop and the way large the step size is, here the default is 1.

In the event you pass just one value to the range() function, then that is mechanically the stop value with start value 0 and step length 1.

By passing two values, you set the beginning value and the stop value:

As already described, all lines of code which are indented after the for loop are executed in each pass. This permits you to map more complex relationships and include an if-else loop, for instance:

To this point now we have learned that the Python for-loop all the time has a line break after the colon and continues with an indentation on the following line. To make the code more compact or to avoid wasting time, there’s also the chance to jot down a Python for-loop in a single line, depending on how complex it’s. The instance above, which outputs the numbers between 2 and 5, will be written very easily in a single line:

With more complex for-loops, the representation in a single line may also quickly change into confusing, as our example with the even and odd numbers shows:

Particularly elegant is the creation of a list or a dictionary using a for-loop, which is then normally also defined in a line:

In the event you were to resolve this with a “regular” Python for-loop, you’ll first should create an empty list after which fill it little by little. That is far more cumbersome:

A Python for-loop shouldn’t all the time run to the tip of the loop. In some cases, it may also make sense to finish the sequence early. For this purpose, you should utilize the “break” command. In the next example, the loop is interrupted as soon as the present number is larger than 4.

The command “proceed” is the precise opposite of “break” and causes the loop to proceed running. It is sensible especially for those who wouldn’t have a direct command to execute for a condition, but just want to start out a round within the loop.

In the next example, we only wish to output the numbers which are greater than 4. To do that, we skip all values which are lower than or equal to 4 using “proceed”. This can output only the numbers from five upwards:

With the assistance of “enumerate” you may not only iterate through the weather of an object, resembling a list but in addition get the index of the respective element at the identical time. This may make sense, for instance, if you need to change the weather of a list directly.

Suppose we wish to multiply each odd number within the “numbers” list by two. To do that, we iterate through the “numbers” object using “enumerate” and alter the number within the list if the element is odd. It is necessary to notice here that we must now assign two names since each iteration step has two variables, namely the index and the element itself.

Here it can be crucial to know that changes to the item you’re iterating over don’t have any effect on the Python for-loop. It still looks at the item because it did on the very first pass. The next command would otherwise should end in an infinite loop because the “numbers” element becomes twice as long in each pass because it was before. Nevertheless, the Python for-loop has only nine steps, because at first of the loop the item “numbers” had only nine elements.

  • The Python for-loop is used to iterate dynamically through elements of an object.
  • With the assistance of “break” you may end a loop prematurely.
  • The command “enumerate” not only returns a component in each round but in addition the index of the element in the item. This makes it possible, for instance, to vary the item from inside the loop.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here