Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cannot print range function
#1
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 :)
Reply
#2
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)
I am trying to help you, really, even if it doesn't always seem that way
Reply
#3
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).
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  print doesnt work in a function ony 2 383 Mar-11-2024, 12:42 PM
Last Post: Pedroski55
  How to print variables in function? samuelbachorik 3 978 Dec-31-2022, 11:12 PM
Last Post: stevendaprano
  How to print the output of a defined function bshoushtarian 4 1,393 Sep-08-2022, 01:44 PM
Last Post: deanhystad
  Why does absence of print command outputs quotes in function? Mark17 2 1,447 Jan-04-2022, 07:08 PM
Last Post: ndc85430
  return vs. print in nested function example Mark17 4 1,841 Jan-04-2022, 06:02 PM
Last Post: jefsummers
  matplotlib x axis range goes over the set range Pedroski55 5 3,333 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  output correction using print() function afefDXCTN 3 11,285 Sep-18-2021, 06:57 PM
Last Post: Sky_Mx
  print function output wrong with strings. mposwal 5 3,236 Feb-12-2021, 09:04 AM
Last Post: DPaul
  Output with none, print(x) in function Vidar567 3 2,587 Nov-24-2020, 05:40 PM
Last Post: deanhystad
  print function help percentage and slash (multiple variables) leodavinci1990 3 2,551 Aug-10-2020, 02:51 AM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020