[Introduction to Python] How to iterate with the range function?

Reference site: [Introduction to Python] How to iterate with the range function?

[Introduction to Python] How to iterate with the range function?

In Python, the for statement may be used to repeat the process a certain number of times. At that time, you can prepare a list of numerical values and rotate it by that length, but using range makes it easier to write something like Python.

This time, I will explain how to use range in Python.

How to use range

If you want to repeat the process a certain number of times in Python, you can do it by using the list of the length of the sentence. For example, if you want to repeat 5 times, use a list of length 5.

list1 = [1, 2, 3, 4, 5]
count = 0

for x in list1:
    count += 1
    
print('Number of loops:{}'.format(count))

Execution result

Loop count: 5

This method is fine, but if you repeat it a long time, for example 100 or 1000 times, it can be tedious and time consuming to have a list of that length.

If you want to repeat the loop a certain number of times, use the range function. The range function is a function that automatically generates a continuous list of integers of a specified length. By combining the for statement and the range function, you can loop as many times as you like.

for variable in range([Starting number,]Last number[,Amount to increase]):
    #Loop processing

The range has three arguments: the starting number, the last number, and the increasing amount, of which the starting number and the increasing amount can be omitted. If you pass a number to range (), it will be the last number, and a list will be created containing the values from 0 to "last number – 1".

count = 0

for x in range(5):
print(x)
    count += 1
    
print('Number of loops:{}'.format(count))

Execution result

0 1 2 3 4 Number of loops: 5

In this example, since 5 is passed to range (), a "list of length 5 with elements from 0 to 4" is created, and elements are taken out one by one from there, so loop 5 times. I can. If you want the first number to be any number instead of 0, enter the "starting number" argument.

count = 0

for x in range(1, 5):
    print(x)
    count += 1
    
    
print('Number of loops:{}'.format(count))

Execution result

1 2 3 4 Number of loops: 4

Changed the argument of range from (5) to (1,5). This resulted in a "list of length 4 with elements from 1 to 4" returned by range, resulting in 4 loops.

You can also freely change the value added to the next element by specifying the "increase amount". This makes it easy to create a list that grows by 2 from 0 to 8 or a list that grows by 3 from 0 to 9.

count = 0

for x in range(0, 10, 2):
    print(x)
    count += 1
    
print('Number of loops:{}'.format(count))

Execution result

0 2 4 6 8 Number of loops: 5

In this example, the start is 0 and the end is 10, but the amount to be increased is 2. Therefore, range will return "a list of length 5 that increases by 2 from 0 to 8", so the number of loops will be 5.

You can also use negative numbers in range. You can also create a reverse-ordered list by reversing the start and end values and increasing the amount to a negative number.

count = 0

for x in range(10, 0, -2):  #Pass a negative number
    print(x)
    count += 1
    
print('Number of loops:{}'.format(count))

Execution result

10 8 6 4 2 Number of loops: 5

Difference from xrange

If your Python version is 2.x.x, there is xrange as a function very similar to range. The usage and execution result of xrange are exactly the same as range.

count = 0

for x in xrange(5):
print(x)
    count += 1
    
print('Number of loops:{}'.format(count))

Execution result

0 1 2 3 4 Number of loops: 5

So what's the difference between range and xrange is that xrange saves memory. range creates a list with the elements specified by the argument, and executes the for statement by extracting the elements from the list. On the other hand, xrange does not execute the for statement after creating the list first, but generates the value as needed when fetching with the for statement. In other words, because it does not create a list, xrange can save memory for the same process.

However, the difference between range and xrange is so small that you usually don't need to use xrange. Basically, you should use range.

Also, in Python3 series, the structure of range became close to xrange, so xrange itself was abolished. Therefore, in the case of Python3 series, it is better to use range without worrying about it.

Recommended Posts

[Introduction to Python] How to iterate with the range function?
[Introduction to Python] How to get data with the listdir function
[Introduction to Python] How to split a character string with the split function
[Python] Explains how to use the range function with a concrete example
[Introduction to Python] How to write a character string with the format function
[Introduction to Udemy Python3 + Application] 44. range function
[Python] Explains how to use the format function with an example
Introduction to Python with Atom (on the way)
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Python] How to specify the download location with youtube-dl
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
[Introduction to Udemy Python3 + Application] 30. How to use the set
[Introduction to Python] How to stop the loop using break?
[Python] How to rewrite the table style with python-pptx [python-pptx]
[Introduction to Python] How to get the index of data with a for statement
Python: How to use async with
How to use the zip function
[Introduction to Python] How to parse JSON
How to get the Python version
How to get started with Python
[Python] How to import the library
How to use FTP with Python
How to calculate date with python
How to use python zip function
I tried to simulate how the infection spreads with Python
How to get into the python development environment with Vagrant
[Introduction to Python] How to use class in Python?
[Python] Set the graph range with matplotlib
[Introduction to Udemy Python3 + Application] 48. Function definition
[Python 3.8 ~] How to define a recursive function smartly with a lambda expression
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
[python] How to use __command__, function explanation
[Introduction to Udemy Python3 + Application] 45. enumerate function
How to work with BigQuery in Python
[Introduction to Udemy Python3 + Application] 41. Input function
[Introduction to Python] Let's use foreach with Python
[Python] Introduction to CNN with Pytorch MNIST
[Introduction to Python] How to use the in operator in a for statement?
How to do portmanteau test with python
How to calculate space background X-ray radiation (CXB) with python by specifying the flux range
How to display python Japanese with lolipop
[Introduction to Udemy Python3 + Application] 46. Zip function
How to enter Japanese with Python curses
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
[Python] How to deal with module errors
How to send a request to the DMM (FANZA) API with python
[Introduction to Python] How to use the Boolean operator (and ・ or ・ not)
The road to compiling to Python 3 with Thrift
How to install python3 with docker centos
The 16th offline real-time how to write problem was solved with Python
How to crop the lower right part of the image with Python OpenCV
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[Introduction to Python] How to judge authenticity with if statement (True and None)
The 16th offline real-time how to write reference problem to solve with Python
How to get the date and time difference in seconds with python
[Python] How to use the enumerate function (extract the index number and element)
[Python] How to set the (client) window size inside the browser with Selenium
The 19th offline real-time how to write reference problem to solve with Python
The 15th offline real-time how to write problem was solved with python
[Introduction to Python] What is the method of repeating with the continue statement?
How to upload with Heroku, Flask, Python, Git (4)