0

What does asterisk (*) represent while declaring variable in Python and how to print them?

E.g a,b,*c,d = 1,2,3

15th Aug 2019, 11:01 AM
Bhuwan Khadka
Bhuwan Khadka - avatar
3 Antworten
+ 2
BhuWan KhaDka It's a way to separate the different values of a tuple into different variables. For example: a, b, c = (1, 2, 3) After running this code, you'll have three variables, each with one of the values of the tuple (in order: the first variable will hold the first item of the tuple and so). In essence, it automatizes doing: tup = (1,2,3) a = tup[0] b = tup[1] c = tup[2] Of course, it would raise an error if there are more values than variables. However you can bypass this by using (*) before a variable. (* ) means "save here all the extra values than don't fit with this number of variables". if we have: tuple = (1,2,3,4) a, b, c = tuple This would raise an error, because we have more values in the tuple than variables. However, if we use * in c: a, b, *c = tuple then we'd have a = 1 b = 2 and c = [3,4] Continue....
15th Aug 2019, 11:19 AM
DishaAhuja
DishaAhuja - avatar
0
a variable name with "*" means that it contains all the left items after assigning values to"all" variables without an "*".in your example,*c is empty,because after assigning to a,b,d no*hing left for c
15th Aug 2019, 11:13 AM
Iqbal Khan
Iqbal Khan - avatar
0
In this way you are using this astrek symbol for the unpacking of tuples sometime when two elements are unpacked in one variable then it make that variable an list in case of 'c' in above code is an list (it's a list as more element are present, not a tuple, at least in python 3.6.5). You can use (*) in whatever variable you want, but the values will be assigned in order. a, *b, c = tuple a = 1 b= [2,3] c = 4 Have some 🍎 🍎 🍎 🍎 For some more uses reference are mention below. https://medium.com/understand-the-python/understanding-the-asterisk-of-python-8b9daaa4a558 https://www.sololearn.com/Discuss/1695602/?ref=app
15th Aug 2019, 11:19 AM
DishaAhuja
DishaAhuja - avatar