* with lists in python | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
- 1

* with lists in python

Can anyone explain me how when we use *(asterisk) with lists in python. Particularly when we want to print the entire contents of the list. I generally go with a for each loop to print them. But i seen in many online submissions they use *listname to print list elements with spaces. Please clarify my doubt? example: l=[1,2,3,4,5] for i in l: print(i,end=" ") is same as, print(*l) why?

14th May 2021, 3:06 AM
SAKKURI BHANU PRAKASH
1 Antwort
+ 7
* is the destructuring operator in python (when used as unary operator)... when you apply it to a list inside a function argument, it act as if you pass eaxh list elements as arguments to the function (meaning that the function should accept any number of unnamed arguments, as the 'print' function is designed)... in you example, print(*l) is equivalent to print(l[0],l[1],l[2],l[3],l[4])... however, the loop you provide doesn't send a final new line, while the print(*l) default do ^^ anyway, you could also define another separator than the default space used, by specifing a 'sep' named argument as you specified the 'end' one ;)
14th May 2021, 3:21 AM
visph
visph - avatar