Comparison of Python3enumrate and range and Detailed Explanation of Examples

  • 2021-07-18 08:10:48
  • OfStack

Preface

In Python, enumrate and range are commonly used in for loops, enumrate functions are used to loop lists and elements at the same time, while range () functions can generate lists with varying numerical ranges, and can be used in for loops, that is, they are iterative.

Overview of range

range is used to generate a list of consecutive or step-size numeric elements. Here are some basic usage and scenario examples.

Generate a digital sequence


#  Produce 0-9 Sequence of 
for i in range(0, 10):
 print(i)
print('-' * 40)
#  Produce 0-20 , step ( Interval ) For 3 A sequence consisting of digital elements of  
for j in range(0, 21, 3):
 print(j)

Example results:


0
1
2
3
4
5
6
7
8
9
----------------------------------------
0
3
6
9
12
15
18

Using range to traverse the modification list

The most common usage scenario of range is to modify the circular modification list, that is, to use range to build the index circular modification list of the list.


L = [1,2,3,4,5]
for i in range(len(L)):
 L[i] = L[i] ** 2
 print(L[i])

Example results:


1
4
9
16
25

Overview of enumrate

What happens when we want to get the index and sequence elements of a sequence? We can use enumrate to iterate the index and element of the sequence at the same time.


L = [1,2,3,4,5]
for i, value in enumerate(L):
 print(i, '-->',value)
0 --> 1
1 --> 2
2 --> 3
3 --> 4
4 --> 5

Related articles: