Discussion:
[Tutor] Unpack from list
Sunil Tech
2015-07-13 12:03:03 UTC
Permalink
Hi Tutor,


[a,b,c] = [1,2]
this will give
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

But is there any chance, if there are 3 values on left hand side and 2
values on right side, to add an empty value to the left side dynamically?

there can be multiple elements to unpack depending on what is expected on
left side.
Like in methods there can be optional parameters, if the values is not
passed, optional values will take what is been declared.

def optal(a,b,c=''):

"""

c - is option

"""

​Thanks,
Sunil. G

_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.pyt
Mark Lawrence
2015-07-13 12:27:13 UTC
Permalink
Post by Sunil Tech
Hi Tutor,
[a,b,c] = [1,2]
this will give
File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
But is there any chance, if there are 3 values on left hand side and 2
values on right side, to add an empty value to the left side dynamically?
You need "Extended Iterable Unpacking" as described in
https://www.python.org/dev/peps/pep-3132/

<quote>
Post by Sunil Tech
a, *b, c = range(5)
a
0
Post by Sunil Tech
c
4
Post by Sunil Tech
b
[1, 2, 3]
<quote>

Hence:-
Post by Sunil Tech
a,b,*c=[1,2]
a,b,c
(1, 2, [])
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Alan Gauld
2015-07-13 21:16:28 UTC
Permalink
Post by Mark Lawrence
Hence:-
a,b,*c=[1,2]
a,b,c
(1, 2, [])
Neat! a new one on me.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Continue reading on narkive:
Loading...