Purpose of '*' with list in python

Hi,
Somebody please tell me what is the purpose of asterisk in the following python code:

list1 = [10, 20, 4, 45, 99]
# sorting the list
list1.sort()
# printing the first element
print("Smallest element is:", *list1[:1])

I know list1[:1] means everything before index 1.

Zulfi.

According to SO

The * operator unpacks an argument list. It allows you to call a function with the list items as individual arguments.

1 Like

Hi,
Thanks for stack exchange link. I found that *list1[:1] returns, 4 but list1[:1] returns [4]. One is array (or list) containing 4 but other is only value 4.

So we can use both the answers. Any comments?
Zulfi.

Hi my friends,
I found a disparity. list1[-1] does not return [99] but 99. I think this is a problem.

Zulfi.

Hi @Zulfi6000, if you want a list containing only the last element you need to add a colon like list1[-1:] – meaning a slice from the last element to the end of the list.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.