Hướng dẫn xrange in python w3schools

❮ Built-in Functions

Example

Create a sequence of numbers from 0 to 5, and print each item in the sequence:

x = range[6]
for n in x:
  print[n]

Try it Yourself »

Definition and Usage

The range[] function returns a sequence of numbers, starting from 0 by default, and increments by 1 [by default], and stops before a specified number.

Syntax

Parameter Values

ParameterDescription
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at which position to stop [not included].
step Optional. An integer number specifying the incrementation. Default is 1

More Examples

Example

Create a sequence of numbers from 3 to 5, and print each item in the sequence:

x = range[3, 6]
for n in x:
  print[n]

Try it Yourself »

Example

Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:

x = range[3, 20, 2]
for n in x:
  print[n]

Try it Yourself »

❮ Built-in Functions


Python Tutorial

❮ Home Next ❯

Learn Python

Python is a popular programming language.

Python can be used on a server to create web applications.

Start learning Python now »

Learning by Examples

With our "Try it Yourself" editor, you can edit Python code and view the result.

Example

print["Hello, World!"]

Try it Yourself »

Click on the "Try it Yourself" button to see how it works.

Python File Handling

In our File Handling section you will learn how to open, read, write, and delete files.

Python File Handling

Python Database Handling

In our database section you will learn how to access and work with MySQL and MongoDB databases:

Python MySQL Tutorial

Python MongoDB Tutorial

Python Exercises

Test Yourself With Exercises

Exercise:

Insert the missing part of the code below to output "Hello World".

["Hello World"]

Start the Exercise

Python Examples

Learn by examples! This tutorial supplements all explanations with clarifying examples.

See All Python Examples

Python Quiz

Test your Python skills with a quiz.

Python Quiz

My Learning

Track your progress with the free "My Learning" program here at W3Schools.

Log into your account, and start earning points!

This is an optional feature, you can study W3Schools without using My Learning.

Python Reference

You will also find complete function and method references:

Reference Overview

Built-in Functions

String Methods

List/Array Methods

Dictionary Methods

Tuple Methods

Set Methods

File Methods

Python Keywords

Python Exceptions

Python Glossary

Random Module

Requests Module

Math Module

CMath Module

Download Python

Download Python from the official Python web site: //python.org


Kickstart your career

Get certified by completing the course

Get certified

w3schoolsCERTIFIED.2022

❮ Home Next ❯


Range[] và xrange[] là hai hàm mà ta có thể sử dụng để lặp một số lần nhất định ở vòng lặp for trong Python. Trong Python 3, không có hàm xrange, nhưng hàm range hoạt động giống như xrange trong Python 2. Nếu bạn muốn viết code sẽ chạy trên cả Python 2 và Python 3, bạn nên sử dụng hàm range[].

range[] – Hàm này trả về một đối tượng range [một loại lặp lại].
xrange[] – Hàm này trả về đối tượng generator có thể được sử dụng để hiển thị các số chỉ bằng cách lặp. Chỉ có range cụ thể được hiển thị theo yêu cầu và do đó được gọi là lazy evaluation.

Cả hai đều được thực hiện theo những cách khác nhau và có những đặc điểm khác nhau liên quan đến chúng. Các điểm so sánh là:

  • Kiểu trả về
  • Bộ nhớ
  • Sử dụng hoạt động
  • Tốc độ
  • 1. Kiểu trả về
  • 2. Bộ nhớ
  • 3. Sử dụng hoạt động 
  • 4. Tốc độ
  • 5. Điểm quan trọng:

1. Kiểu trả về

range[] trả về – đối tượng range .
xrange[] trả về – đối tượng xrange [] .

# -----------------------------------------------------------
#Cafedev.vn - Kênh thông tin IT hàng đầu Việt Nam
#@author cafedevn
#Contact: 
#Fanpage: //www.facebook.com/cafedevn
#Group: //www.facebook.com/groups/cafedev.vn/
#Instagram: //instagram.com/cafedevn
#Twitter: //twitter.com/CafedeVn
#Linkedin: //www.linkedin.com/in/cafe-dev-407054199/
#Pinterest: //www.pinterest.com/cafedevvn/
#YouTube: //www.youtube.com/channel/UCE7zpY_SlHGEgo67pHxqIoA/
# -----------------------------------------------------------

# Python code to demonstrate range[] vs xrange[] 
# on  basis of return type 
  
# initializing a with range[] 
a = range[1,10000] 
  
# initializing a with xrange[] 
x = xrange[1,10000] 
  
# testing the type of a 
print ["The return type of range[] is : "] 
print [type[a]] 
  
# testing the type of x 
print ["The return type of xrange[] is : "] 
print [type[x]] 

Kết quả:

The return type of range[] is : 

The return type of xrange[] is : 

2. Bộ nhớ

Biến lưu trữ range được tạo bởi hàm range[] chiếm nhiều bộ nhớ hơn so với biến lưu trữ range sử dụng xrange []. Lý do cơ bản cho điều này là kiểu trả về của range[] là list còn đối với xrange[], kiểu trả về là đối tượng xrange[].

# -----------------------------------------------------------
#Cafedev.vn - Kênh thông tin IT hàng đầu Việt Nam
#@author cafedevn
#Contact: 
#Fanpage: //www.facebook.com/cafedevn
#Group: //www.facebook.com/groups/cafedev.vn/
#Instagram: //instagram.com/cafedevn
#Twitter: //twitter.com/CafedeVn
#Linkedin: //www.linkedin.com/in/cafe-dev-407054199/
#Pinterest: //www.pinterest.com/cafedevvn/
#YouTube: //www.youtube.com/channel/UCE7zpY_SlHGEgo67pHxqIoA/
# -----------------------------------------------------------

# Python code to demonstrate range[] vs xrange[] 
# on  basis of memory 
  
import sys 
  
# initializing a with range[] 
a = range[1,10000] 
  
# initializing a with xrange[] 
x = xrange[1,10000] 
  
# testing the size of a 
# range[] takes more memory 
print ["The size allotted using range[] is : "] 
print [sys.getsizeof[a]] 
  
# testing the size of a 
# range[] takes less memory 
print ["The size allotted using xrange[] is : "] 
print [sys.getsizeof[x]] 

Kết quả:

The size allotted using range[] is : 
80064
The size allotted using xrange[] is : 
40

3. Sử dụng hoạt động 

Vì range[] trả về list, nên tất cả các hoạt động có thể được áp dụng trong list có thể được sử dụng trên đó. Mặt khác, vì xrange[] trả về đối tượng xrange, các hoạt động liên quan đến list không thể được áp dụng trên nó, dẫn đến việc bất lợi.


# Python code to demonstrate range[] vs xrange[] 
# on  basis of operations usage  
  
# initializing a with range[] 
a = range[1,6] 
  
# initializing a with xrange[] 
x = xrange[1,6] 
  
# testing usage of slice operation on range[] 
# prints without error 
print ["The list after slicing using range is : "] 
print [a[2:5]] 
  
# testing usage of slice operation on xrange[] 
# raises error 
print ["The list after slicing using xrange is : "] 
print [x[2:5]] 

Lỗi:

Traceback [most recent call last]:
  File "1f2d94c59aea6aed795b05a19e44474d.py", line 18, in 
    print [x[2:5]]
TypeError: sequence index must be integer, not 'slice'

Kết quả:

The list after slicing using range is : 
[3, 4, 5]
The list after slicing using xrange is : 

Do thực tế là hàm xrange[] chỉ đánh giá đối tượng generator mà chỉ chứa các giá trị lazy evaluation yêu cầu , do đó, nó sẽ triển khai nhanh hơn hàm range[].

5. Điểm quan trọng:

  • Nếu bạn muốn viết mã sẽ chạy trên cả Python 2 và Python 3, hãy sử dụng hàm range[] vì hàm xrange không được dùng trong Python 3
  • range[] nhanh hơn nếu lặp trên cùng một chuỗi nhiều lần.
  • xrange[] phải xây dựng lại đối tượng số nguyên mỗi lần, còn range[] lại có các đối tượng nguyên thực. [Tuy nhiên, nó sẽ luôn hoạt động kém hơn về mặt bộ nhớ]

Nguồn và Tài liệu tiếng anh tham khảo:

  • w3school
  • python.org
  • geeksforgeeks

Tài liệu từ cafedev:

  • Full series tự học Python từ cơ bản tới nâng cao tại đây nha.
  • Ebook về python tại đây.
  • Các series tự học lập trình khác

Nếu bạn thấy hay và hữu ích, bạn có thể tham gia các kênh sau của cafedev để nhận được nhiều hơn nữa:

  • Group Facebook
  • Fanpage
  • Youtube
  • Instagram
  • Twitter
  • Linkedin
  • Pinterest
  • Trang chủ

Chào thân ái và quyết thắng!

Đăng ký kênh youtube để ủng hộ Cafedev nha các bạn, Thanks you!

Chủ Đề