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)
If you want to create a list of numbers from 1 to 100, you simply do:
range(1, 101)
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.