Counter in for loop python

How to Count in Python Loop

This tutorial discusses about how to count in Python loop.

Count in a Loop in Python

In Python, we have many objects that can be treated as iterable. An iterable is an object like a list, tuple, or any other sequence of elements that can be iterated using a simple for loop.

Counting in a loop means making a note of every iteration to find the total number of iterations after the loop has stopped running.

How to Count in A Loop in Python

This tutorial will demonstrate ways how to count in a loop in Python.

Using a Counter Variable to Count in A Loop in Python

This method is very straightforward. We will declare a variable outside the loop and assign it a value of zero. In every iteration, we will increment its value and print it.

In the above example, we create a list lst that contains three elements. The variable c is initialized with zero. We use the for loop to iterate over this list. In every iteration, we increment the variable c and print its value.

Further reading:

How to decrement for loop in python
For Loop Increment By 2 in Python

Using the enumerate() Function to Count in A Loop in Python

The enumerate() function takes an iterable and assigns a counter variable to each element. This way, every element gets assigned a value that can act as the index of the element.

We can use this index variable to act as a counter variable for the loop.

In the above example, we display the index of the element after using the enumerate() function and iterating it. Note that the index starts from 0.

Using the zip() Function to Count in A Loop in Python

The zip() function can be used to combine two iterables into one by combining the individual elements at corresponding positions together.

Читайте также:  Java constants or enums

We can create a list of the length iterable with the range() function. The two can be then combined to create a new iterable. This method is just another way to emulate the enumerate() function discussed previously.

The code is demonstrated below.

The range() function returns an object containing a sequence to the length of the list. This is combined with the list and the counter value is displayed.

Conclusion

To conclude, we discussed how to count in a loop in Python. In the first method, we initialize a variable and increment it in every iteration. The other methods involve the enumerate() and zip() functions to create an index for the iterable that can act as a counter variable.

That’s all about how to count in Python loop.

Was this post helpful?

You may also like:

Count Unique Values in NumPy Array

Create Array of Arrays in Python

Convert String List to Integer List in Python

Convert Object to Float in Pandas

NameError: Name requests Is Not Defined

Python Hex to String

NameError: Name xrange Is Not Defined in Python

Call Python Script from Bash with Arguments

TypeError: ‘dict_values’ Object Is Not Subscriptable

Python Sleep Milliseconds(ms) with examples

Share this

Author

Count unique values in numpy array

Count Unique Values in NumPy Array

Table of ContentsUse np.unique() method to display unique valuesUse np.unique() method with len() functionUse np.unique() Method with return_counts as true Use np.unique() method to display unique values Use np.unique() to display unique values in numpy array. [crayon-64b973c6ae9e4358870589/] Running the above code will display the following output on the console: [crayon-64b973c6ae9ec861757139/] np.unique() method finds unique values […]

Create array of arrays in Python

Create Array of Arrays in Python

Table of ContentsUse numpy.array() FunctionManually create array of arraysUse numpy.append() Function Use numpy.array() Function To create an array of the arrays in Python: Use the np.array() function to create a numpy.ndarray type array of the arrays. [crayon-64b973c6aeb7b594693685/] [crayon-64b973c6aeb7f724812580/] The Python library NumPy scientifically computes advanced numerical work. It is a language extension that adds support […]

Convert String List to Integer List in Python

Convert String List to Integer List in Python

Table of ContentsUsing map() MethodUsing for LoopUsing List ComprehensionUsing eval() and ast.literal_eval() MethodsUsing User-defined Function Using map() Method Use the map() method with list() method to convert string list to integer list in Python. [crayon-64b973c6aeca7472788373/] [crayon-64b973c6aecaa376377379/] First, we defined a variable named string_list and set its value to a list having five string values. Next, […]

Convert Object to Float in Pandas

Convert Object to Float in Pandas

Table of ContentsUsing astype() MethodUsing to_numeric() Method Using astype() Method Use the astype() method to convert one DataFrame column from object to float in pandas. [crayon-64b973c6aeefa804174788/] [crayon-64b973c6aeefd561103808/] Use the astype() method to convert multiple DataFrame s from object to float in pandas. [crayon-64b973c6aeeff892488513/] [crayon-64b973c6aef00293902062/] Use the astype() method to convert the entire DataFrame from object […]

Читайте также:  Python sqlite3 data types

NameError name requests is not defined

NameError: Name requests Is Not Defined

Table of ContentsReproducing NameError in PythonPossible Solutions to Fix NameError in PythonSolution 1: pip Module InstallationInstall pip using Python 3Check Your import StatementSolution 2: requests Module is Out of Nested ScopeSolution 3: requests Module Imported into the Global Python has a name error when you try to use a variable or function that is not […]

Python hex to String

Python Hex to String

Table of ContentsUsing bytes.fromhex() MethodUsing binascii ModuleUsing codecs ModuleUsing List Comprehension The representation of data in Hexadecimal is commonly used in computer programming. It is used to represent binary data in a human-readable form, as understanding the machine language (i.e., Binary) is difficult for humans. Hexadecimal notation is used in networking protocols, e.g., IPv6 and […]

Источник

Counter in for loop python

Last updated: Feb 19, 2023
Reading time · 5 min

banner

# Table of Contents

# Count in a for loop in Python

Use the enumerate() function to count in a for loop.

The function takes an iterable and returns an object containing tuples, where the first element is the index, and the second is the item.

Copied!
my_list = ['a', 'b', 'c'] # ✅ count in for loop for index, item in enumerate(my_list): print(index, item) # 👇️ # 0 a # 1 b # 2 c

count in for loop

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index, and the second is the item.

We can directly unpack the index (or count) and the item in our for loop.

Copied!
my_list = ['a', 'b', 'c'] for index, item in enumerate(my_list): print(index, item) # 👇️ # 0 a # 1 b # 2 c

directly unpack index and item in for loop

The enumerate function takes an optional start argument, which defaults to 0 .

Note: if you need to count in a WHILE loop, click on the following subheading:

# Count in a for loop starting from a different number

If you need to start the count from a different number, e.g. 1 , specify the start argument in the call to enumerate() .

Copied!
my_list = ['a', 'b', 'c'] for count, item in enumerate(my_list, start=1): print(count, item) # 👇️ # 1 a # 2 b # 3 c

count in for loop starting at different number

The count variable has an initial value of 1 and then gets incremented by 1 on each iteration.

Alternatively, you can manually count in the for loop.

# Counting in a for loop manually in Python

This is a three-step process:

  1. Initialize a count variable and set it to a number.
  2. Use a for loop to iterate over a sequence.
  3. On each iteration, reassign the count variable to its current value plus N.
Copied!
my_list = ['a', 'b', 'c'] count = 0 for item in my_list: count += 1 print(count) print(count) # 👉️ 3

We declared a count variable and initially set it to 0 .

The following 2 lines of code achieve the same result:

Here is an example that uses the longer reassignment syntax.

Copied!
my_list = ['a', 'b', 'c'] count = 0 for item in my_list: count = count + 1 print(count) print(count) # 👉️ 3

# Counting in a for loop using range()

You can also use the range() class to count in a for loop.

Copied!
a_list = ['bobby', 'hadz', 'com'] for index in range(len(a_list)): # 0 bobby # 1 hadz # 2 com print(index, a_list[index])

The range class creates an iterator object of the specified length.

Читайте также:  Adding days calendar java

This approach is very similar to using enumerate() , however, the enumerate function is more convenient and direct.

# Counting in a While loop in Python

  1. Declare a count variable and set it to 0 .
  2. Use a while loop to iterate as long as count is less than N.
  3. On each iteration, increment the value of the count variable by 1 .
Copied!
count = 0 max_count = 5 while count max_count: count += 1 print(count) # 👉️ 1 2 3 4 5

counting in while loop in python

We declared a count variable and set it to 0 .

The max_count variable is used in the condition of the while loop.

The while loop keeps iterating until the value of count is equal to or greater than the value of max_count .

On each iteration, we increment the value of the count variable by 1 to move towards the case where the condition is no longer met.

# Counting how many times a while loop runs

You can also use this approach to count how many times a while loop runs.

Copied!
count = 0 my_list = ['bobby', 'hadz', 'com'] while len(my_list) > 0: my_list.pop() count += 1 print(count) # 👉️ 1 2 3 print(count) # 👉️ 3

count how many times while loop runs

On each iteration of the while loop, we increment the count variable and remove an item from a list.

The while loop keeps iterating and counting until the list is empty.

The += operator is a shorthand for count = count + 1 .

The following code sample achieves the same result using the more verbose syntax.

Copied!
count = 0 my_list = ['bobby', 'hadz', 'com'] while len(my_list) > 0: my_list.pop() count = count + 1 print(count) # 👉️ 1 2 3 print(count) # 👉️ 3

If you don’t have a condition and only need to iterate N times and keep track of the count, you can also use the range() class.

The range class is commonly used for looping a specific number of times in for loops and takes the following arguments:

Name Description
start An integer representing the start of the range (defaults to 0 )
stop Go up to, but not including the provided integer
step Range will consist of every N numbers from start to stop (defaults to 1 )

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

Copied!
for n in range(5): print(n) result = list(range(5)) # 👇️ [0, 1, 2, 3, 4] print(result)

The example shows that if the start argument is omitted, it defaults to 0 and if the step argument is omitted, it defaults to 1 .

If values for the start and stop parameters are provided, the start value is inclusive, whereas the stop value is exclusive.

Copied!
result = list(range(1, 5)) # 👇️ [1, 2, 3, 4] print(result)

The range() class is more intuitive to use if you know how many times you need to iterate in advance.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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