Programming
python python-3.x range sequence
Updated Sat, 04 Jun 2022 17:55:28 GMT

What does * do with range() in python?


I was doing a Hackerrank python problem the task was to print 123...N (where N is the input) without using any string function.

Someone commented a solution which is:

print(*range(1, int(input())+1), sep='')

My question is:

  1. What is the use of * here with this range() function?
  2. Why we can't do it by only using range() function inside the print?
  3. Is there any other way to do this?



Solution

You are executing this, essentially,

n = int(input())
print(*range(1, n + 1), sep='')

1.) The star *args syntax lets you fill in arguments from an iterable. For example, these are all equivalent:

def foo(a, b):
    return a + b
foo(1, 2)
lst = [1, 2]
foo(*lst)
tup = (1, 2)
foo(*tup)

2.) Certainly you can use just range without unpacking *args. See next item.

3.) Another way would be to print within a for loop, or more compactly to create a string s:

s = "".join(map(str, range(1, n + 1)))
print(s)




Comments (1)

  • +0 – Is not "".join string function and task requriement without using any string function? — May 05, 2020 at 17:01  


External Links

External links referenced by this document: