简体   繁体   中英

How do I fast make a list of 1~100?

When I was a python beginner, I could create a multiple lines for loop that make a list of 1~100:

a=[]
for i in range(1,101):
    a.append(i)

When I knew how to write a single line for loop, I could simply my code.

a=[ _ for _ in range(1,101)]

When I review python document and relearn python in detail now, I find range() built-in function it can directly make a list, but I look no one doing this. Why?

a=range(1,101)

In Python 2.x

If you want to create a list of numbers from 1 to 100, you simply do:

range(1, 101)

In Python 3.x

range() no longer returns a list, but instead returns a generator. We can easily convert that into a list though.

list(range(1, 101))

When I review python document and relearn python in detail now, I find range() built-in function it can directly make a list, but I look no one doing this.

Depends, if you are using Python 2.X it does but for Python 3.X it produces a range object which should be iterated upon to create a list if you need to.

But in any case for all practical purpose extending a range object as a List comprehension is useless and have an unnecessary memory hogging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM