-2

I have this code to segregate odd and even numbers . Can't understand why is there a star mark (*) when printing lists of odd and even in the last :

print(*even) print(*odd) what does the star imply , what happens if we don't use it

odd = []
even = []
# number of elemetns as input
n = int(input())
# elements as input
elements = list(map(int,input().split()))

#loop running across all elements
for element in elements:
    #if even, append to even[]
    if element%2 == 0:
        even.append(element)
    else:
        odd.append(element)

#print as a list delimited by space, without brackets
print(*even)
print(*odd)

#Code ends know it's a part of whole syntax of python print statement of using multiple objects , but still unclear .

4 Answers4

0

As written in your own comment in the code:

print as a list delimited by space, without brackets

a = [1,2,3,4] 
print(*a)

Output:

1 2 3 4

And,

print(a)

Output:

[1, 2, 3, 4]

starred expressions have many benefits like

print(*a,sep='\n')

Can replace

for i in a:
    print(a)
Bibhav
  • 1,579
  • 1
  • 5
  • 18
0

(*) Operator used to unpack the numbers of arguments

without (*)operator print function
list1 = [1,2,3,4,5]
print(list1)
Output:
[1,2,3,4,5]

With (*) operator print function
list1 = [1,2,3,4,5]
print(*list1)
Output:
1, 2, 3, 4, 5
  • This answer lacks any explanation of itself, look at the other answers. – Tony Williams Apr 04 '22 at 04:55
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 04 '22 at 04:55
-1

The star gets rid of the normal list formatting.

#print(*even):
2 4 6

#print(even):
[2, 4, 6]
-1

This allows you to print a list without having spaces or brackets, look at this link under "Unpacking a function using positional argument."

https://www.geeksforgeeks.org/python-star-or-asterisk-operator/

Andrew Jouffray
  • 109
  • 2
  • 9