Python Forum

Full Version: Cannot print range function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am using instructions for an older version of Python, so probably some change.
I'm looking for the equivalent of:

Typing a basic range
>>> range(10)

Then hitting enter to display it on one line

range(10)
[0,1,2,3,4,5,6,7,8,9]


the closest solution I've found online is using a for loop, and displaying each element on a separate line without brackets.


This is probably a very small question to be stuck on, but any help for a newbie is appreciated :)
You want a list (unless you want to print the square brackets literally).

Several techniques:

print(list(range(10)))

nums = [x for x in range(10)]
print(nums)

nums = []
for idx in range(10):
    nums.append(idx)
print(nums)
to add to what gruntfutuk explained - you probably use python2 teaching materials where range will return list. But you are using python3 (good!) so range will return range object - more memory efficient, because it does not create the whole list in memory. from docs:
Quote:The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).