+ 2
What does it happen in this code?
I took this code in Python's tutorial about the range function. I would like to know how catch the addres of a variable, but I didn't get it. So, I put "*" before the list's name, and the output was a few different of the previous output. If someone know what it happened, please, could explain me? https://code.sololearn.com/c911gd0RF6Zt/?ref=app
10 odpowiedzi
+ 4
The asterisk (*) denotes iterable unpacking: it sort of removes the container and produces a sequence out of the elements inside. So while print(range(5)) would print the range object "range(0, 5)", print(*range(5)) would print "0 1 2 3 4", as it is the same as print(0, 1, 2, 3, 4). What happens with your code is similar. print(*numbers) just prints the elements inside numbers.
Now, to get the address of an object you can use the id() function. Try print(id(numbers)).
https://docs.python.org/3/library/functions.html#id
+ 4
David Arumba , try this:
print(*range(10), sep='\n')
The optional sep keyword species the separator between the objects to be printed. It's default value is a single space ' '. You can experiment with it, like print(*range(3), sep='#x27;) would print 0$1$2.
+ 2
You are welcome, Gabriel! ☺
+ 2
Thank you Kishalaya Saha I never knew about the keyword
+ 2
Gabriel Felix dos Santos the for loop also worked,thank you
+ 1
The address of the first variable is always 0 and the address of the last variable is the range - 1
+ 1
Thank youu so much ✌✌
+ 1
Kishalaya Saha suppose I wanted to print the values vertically,..how would i do it?
I.e
0
1
2
3
4
5
6
....
+ 1
David Arumba, I dunno how do it using the asterisk "*", but you could create a for-loop and print each element concatened with "\n". For example, it would be like this:
for element in numbers:
print(str(element) + "\n")
However, maybe there is another way more speed and easy.
0
Gabriel Felix dos Santos the for loop also worked,thank you