Timing loops in python

SOLVED: How to loop n times in Python [10 Easy Examples]

Python provides two different types of looping statements. Here, while loop is similar to the other programming language like C/C++ and Java. Whereas, the for loop is used for two purpose. First one is to iterate over the sequence like List, Tuple, Set and Dictionary. And the other one is to iterate over the range of numbers.

Using python for loop

This version of for loop will iterate over a sequence of numbers using the range() function. The range() represents an immutable sequence of numbers and is mainly used for looping a specific number of times in for loops. Note that the given end point in the range() is never part of the generated sequence. When you want to access the position along with the values of a sequence, this version of for loop is used.

Syntax

The syntax of for loop is as shown below.

for iterator in range(start, stop, step): block of statements else: block of statements
 for iterator in sequence: block of statements else: block of statements 

Example 1 — Using range function to loop n times

The example here iterates over the range of numbers from 1 to 10 and prints its value. However, if it reaches the number divisible by 5, it will break the loop. Note that in this case, the statement inside the else block will not be printed as the loop stops iterating when the value reaches 5.

for i in range(1, 10): if(i%5==0): break print(i) else: print("This statement gets printed only if the for loop terminates after iterating for given number of times and not because of break statement") 

Example 2 — Iterating over list elements using range() function

When you want to iterate over the sequence one way is to iterate using the for loop given below that gives the position of the desired element. The example below iterates over the list of fruits and returns the position of fruit «Mango».

fruits = ["Apple", "Mango", "Banana", "Pineapple", "Strawberry"] for i in range(0, len(fruits)): if(fruits[i]=="Mango"): print("Mango found at position ",(i+1)) break i+=1 
Mango found at position 2


Example 3 — Iterating over list elements without range() function

However, if you just want to operate on the value of the sequence without considering its corresponding position in the sequence, you can use the for loop given below.

 fruits = ["Apple", "Mango", "Banana", "Pineapple", "Strawberry"] for i in fruits: if(i=="Mango"): print("Mango found in the list") break 

Example 4 — Loop n times without index variable

In all our previous examples we have used index variable to process the loop element. Now if we don’t want to use the index variable then you can use the range() in following way:

num = 5 for _ in range(num): print("This will run n number of times the elements present in num")
This will run n number of times the elements present in num This will run n number of times the elements present in num This will run n number of times the elements present in num This will run n number of times the elements present in num This will run n number of times the elements present in num

Alternatively we can also use itertools to achieve the same, here is another example:

import itertools num = 5 for _ in itertools.repeat(None, num): print(f"I will repeat myself times")
I will repeat myself 5 times I will repeat myself 5 times I will repeat myself 5 times I will repeat myself 5 times I will repeat myself 5 times

Example 5 — Nested for loops

However, if you just want to operate on the value of the sequence without considering its corresponding position in the sequence, you can use the for loop given below.

rows=5 for i in range(1, rows + 1): for j in range(1, i + 1): print(j, end=" ") print('')
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

Using python while loop

While loop is also used to iterate over the range of numbers or a sequence. The while loop executes the block until a given condition is satisfied. As soon as the condition becomes false, it will stop executing the block of statements, and the statement immediately after the loop is executed. We can also write the else clause that gets executed if and only if the loop terminates because of false condition and not because of any other exception or break statement.

Читайте также:  Php is last item in array

Syntax

The syntax of for loop is as shown below.

Initialization while condition: block of statements increment/decrement else: block of statements

Example 6 — While with else block

In the example given below, we are having a counter that prints the number from 100 to 105. And, once it reaches the value, the loop terminates and else clause gets executed.

100 101 102 103 104 count value reached

Example 7 — Constructing Dictionary from two list

In the example given below, We have two list containing the name of countries and name of capital respectively. Here, we will read the value from the two lists and construct the dictionary out of this lists.

l1=['India', 'Australia', 'Nepal', 'Bhutan'] l2=['Delhi', 'Canberra', 'Kathmandu', 'Thimphu'] d=<> i=0 while i) i+=1 else: print("Dictionary constructed successfully") print("Retrieving values from Dictionary") print(d) 
Dictionary constructed successfully Retrieving values from Dictionary

Example 8 — While loop inside for loop

In the example given below, we will print the multiplication table of a number till the given number.

for i in range(1, 6): print('Multiplication table of:', i) count = 1 while count < 11: print(i * count, end=' ') count = count + 1 print('\n') 
Multiplication table of: 1 1 2 3 4 5 6 7 8 9 10 Multiplication table of: 2 2 4 6 8 10 12 14 16 18 20 Multiplication table of: 3 3 6 9 12 15 18 21 24 27 30 Multiplication table of: 4 4 8 12 16 20 24 28 32 36 40 Multiplication table of: 5 5 10 15 20 25 30 35 40 45 50

Example 9 - Nested while loop

In the example given below, We will use two while loops that creates a tuples inside the list. Here, we are creating a tuple of two elements as iterator i multiplied by count and i+1 multiplied by count.

[(0, 1), (1, 2)] [(0, 1), (1, 2), (2, 3), (0, 2)] [(0, 1), (1, 2), (2, 3), (3, 4), (0, 3), (0, 2)] [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (0, 4), (0, 3), (0, 2)] [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (0, 5), (0, 4), (0, 3), (0, 2)]

Example-10: Loop n times using while without index number

Читайте также:  Программирование java мобильные устройства

We can also loop through a range of numbers without using the index number:

num = 5 while num > 0: print(f"I will repeat myself times") num -= 1 
I will repeat myself 5 times I will repeat myself 4 times I will repeat myself 3 times I will repeat myself 2 times I will repeat myself 1 times

Summary

The knowledge of looping is core to python programming language that is very useful to formulate a complex logic easily. You will frequently need to use the looping control statements to build varied of applications. The knowledge of looping in different formats and combinations helps solving the really complex task to a time efficient solution. In this tutorial, we covered the for loop and while loop with the different combinations and an example to demonstrate the functionalities of looping. All in all, this tutorial, covers everything that you need to know in order to understand and use the looping in Python.

References

Related Keywords: for loops python, python repeat number n times, python repeat string n times, while loop python, for i in range python, python repeat character n times, for i to n python, python loop n times without index, for loops python, python repeat number n times, python repeat string n times, while loop python, for i in range python, python repeat character n times

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

Python Tutorial

  • Python Multiline Comments
  • Python Line Continuation
  • Python Data Types
    • Python Numbers
    • Python List
    • Python Tuple
    • Python Set
    • Python Dictionary
    • Python Nested Dictionary
    • Python List Comprehension
    • Python List vs Set vs Tuple vs Dictionary
    • Python if else
    • Python for loop
    • Python while loop
    • Python try except
    • Python try catch
    • Python switch case
    • Python Ternary Operator
    • Python pass statement
    • Python break statement
    • Python continue statement
    • Python pass Vs break Vs continue statement
    • Python function
    • Python call function
    • Python argparse
    • Python *args and **kwargs
    • Python lambda function
    • Python Anonymous Function
    • Python optional arguments
    • Python return multiple values
    • Python print variable
    • Python global variable
    • Python copy
    • Python counter
    • Python datetime
    • Python logging
    • Python requests
    • Python struct
    • Python subprocess
    • Python pwd
    • Python UUID
    • Python read CSV
    • Python write to file
    • Python delete file
    • Python any() function
    • Python casefold() function
    • Python ceil() function
    • Python enumerate() function
    • Python filter() function
    • Python floor() function
    • Python len() function
    • Python input() function
    • Python map() function
    • Python pop() function
    • Python pow() function
    • Python range() function
    • Python reversed() function
    • Python round() function
    • Python sort() function
    • Python strip() function
    • Python super() function
    • Python zip function
    • Python class method
    • Python os.path.join() method
    • Python set.add() method
    • Python set.intersection() method
    • Python set.difference() method
    • Python string.startswith() method
    • Python static method
    • Python writelines() method
    • Python exit() method
    • Python list.extend() method
    • Python append() vs extend() in list
    • Create your first Python Web App
    • Flask Templates with Jinja2
    • Flask with Gunicorn and Nginx
    • Flask SQLAlchemy

    Источник

    How To Time Threaded Python Loops Efficiently

    Gain visibility into the speed of your multi-threaded application without sacrificing performance

    I love Python, but sometimes it can be slow as hell. There will always be trade-offs when selecting an interpreted language vs a compiled one, but there are some quirks in Python that can seriously impact performance. One of these quirks that can be easy to overlook, printing.

    When you print some output to the screen in Python it can impact performance so much that some latency-sensitive applications can run into serious problems. Check out: Console output overhead: why is writing to stdout so slow? by Spencer Woo for a deep dive on printing latency.

    In this article, we’ll look at just how slow printing can be and a few ways to actually leverage print statements for timing without grinding your core app code to a screeching halt.

    How fast is a simple loop?

    In this first example below we’ll setup a basic for loop timer and then run it without any print statements, just using pass as we iterate over a range of 1000. This will give us a fast baseline.

    Run this example and you should get a result similar to the following:

    loop time in 
    nanoseconds: 20795
    microseconds: 20.795
    milliseconds: 0.020795

    As you can see, the for loop is pretty quick since it isn’t doing anything. The raw loop completes in about 20 microseconds.

    How much does printing slow us down?

    Now let’s print something inside the loop. Change the example to look like this:

    Источник

Оцените статью