473,549 Members | 2,719 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

unpacking with default values

McA
Hi all,

probably a dumb question, but I didn't find something elegant for my
problem so far.
In perl you can unpack the element of a list to variables similar as
in python
(a, b, c = [0, 1, 2]), but the number of variables need not to fit the
number
of list elements.
That means, if you have less list elements variables are filled with
'undef' (None in python), if you have more list elements as necessary
the rest is ignored.

How can I achieve this behaviour with python in an elegant and fast
way?

Best regards
Andreas Mock
Jul 17 '08 #1
4 4607
McA wrote:
Hi all,

probably a dumb question, but I didn't find something elegant for my
problem so far.
In perl you can unpack the element of a list to variables similar as
in python
(a, b, c = [0, 1, 2]), but the number of variables need not to fit the
number
of list elements.
That means, if you have less list elements variables are filled with
'undef' (None in python), if you have more list elements as necessary
the rest is ignored.

How can I achieve this behaviour with python in an elegant and fast
way?

Best regards
Andreas Mock
--
http://mail.python.org/mailman/listinfo/python-list
Python 3.0 has something a bit like this. Excess values can be bound
(as a list) to the last variable:

a,b,*c = [1,2,3,4,5]

will result in c containing [3,4,5].

In Python 2.x, you can't do that directly, but you should be able to
create a function that lengthens or shortens an input tuple of arguments
to the correct length so you can do:

a,c,b = fix(1,2)
d,e,f = fix(1,2,3,4)

However, the function won't know the length of the left hand side
sequence, so it will have to be passed in as an extra parameter or hard
coded.
Gary Herron

Jul 17 '08 #2
McA
On 17 Jul., 18:33, Gary Herron <gher...@island training.comwro te:
>
In Python 2.x, you can't do that directly, but you should be able to
create a function that lengthens or shortens an input tuple of arguments
to the correct length so you can do:

a,c,b = fix(1,2)
d,e,f = fix(1,2,3,4)

However, the function won't know the length of the left hand side
sequence, so it will have to be passed in as an extra parameter or hard
coded.
Hi Gary,

thank you for the answer.
Do you know the "protocol" used by python while unpacking?
Is it a direct assingnment? Or iterating?

Best regards
Andreas Mock
Jul 17 '08 #3
McA wrote:
On 17 Jul., 18:33, Gary Herron <gher...@island training.comwro te:
>In Python 2.x, you can't do that directly, but you should be able to
create a function that lengthens or shortens an input tuple of arguments
to the correct length so you can do:

a,c,b = fix(1,2)
d,e,f = fix(1,2,3,4)

However, the function won't know the length of the left hand side
sequence, so it will have to be passed in as an extra parameter or hard
coded.

Hi Gary,

thank you for the answer.
Do you know the "protocol" used by python while unpacking?
Is it a direct assingnment? Or iterating?
Both I think, but what do you mean by *direct* assignment?
Best regards
Andreas Mock
--
http://mail.python.org/mailman/listinfo/python-list
It RHS of such an assignment can be any iterable (I think). Lets test:
(The nice thing about an interactive Python session, it that it's really
easy to test.)

>>L = [1,2,3]
a,b,c=L
a,b=L
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>a,b,c,d=L
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack
>>G = (f for f in [1,2,3]) # A generator expression
a,b,c = G
G = (f for f in [1,2,3]) # A generator expression
a,b = G
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>G = (f for f in [1,2,3]) # A generator expression
a,b,c,d = G
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack
I'd call that direct assignment with values supplied by any iterable.

Gary Herron

Jul 17 '08 #4


McA wrote:
Do you know the "protocol" used by python while unpacking?
Is it a direct assingnment? Or iterating?
In CPython, at least, both, just as with normal unpack and multiple
assignment. The iterable is unpacked into pieces by iterating (with
knowledge of the number of targets and which is the catchall). The
targets are then directly bound.
>>from dis import dis
# first standard assignment
>>dis(compile(" a,b,c = range(3)", '','single'))
1 0 LOAD_NAME 0 (range)
3 LOAD_CONST 0 (3)
6 CALL_FUNCTION 1
9 UNPACK_SEQUENCE 3
12 STORE_NAME 1 (a)
15 STORE_NAME 2 (b)
18 STORE_NAME 3 (c)
21 LOAD_CONST 1 (None)
24 RETURN_VALUE
# now starred assignment
>>dis(compile(" a,b,*c = range(3)", '','single'))
1 0 LOAD_NAME 0 (range)
3 LOAD_CONST 0 (3)
6 CALL_FUNCTION 1
9 UNPACK_EX 2
12 STORE_NAME 1 (a)
15 STORE_NAME 2 (b)
18 STORE_NAME 3 (c)
21 LOAD_CONST 1 (None)
24 RETURN_VALUE

The only difference is UNPACK_EX (tended) instead of UNPACK_SEQUENCE .
Tne UNPACK_EX code is not yet in the dis module documentation.
But a little reverse engineering reveals the parameter meaning:
a,*b,c and *a,b,c give parameters 257 and 512 instead of 2.
Separating 2,257,512 into bytes gives 0,2; 1,1; 2,0.
a,*b and *a,b give 1, 256 or 0,1; 1,0. The two bytes
are the number of targets after and before the starred target.

Terry Jan Reedy
Jul 17 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1755
by: george young | last post by:
I came across an cool python feature that I've not seen discussed. This may be *implied* by the language reference manual http://docs.python.org/ref/assignment.html], but it was never obvious to me: An assignment statement can unpack a sequence, binding it's values to explicit names, e.g.: r,g,b = color_tuple and most of us use this...
8
3617
by: Paul McGuire | last post by:
I'm trying to manage some configuration data in a list of tuples, and I unpack the values with something like this: configList = for data in configList: name,a,b,c = data ... do something with a,b, and c Now I would like to add a special fourth config value to "T": ("T",1,5,4,0.005),
3
4556
by: Geoffrey | last post by:
I am working on a file conversion project that reads data from a one file format, reformats in and writes in out to another. The data is records of informations - names address, account number,statistics. The numeric values in the original file are stored in what appears to be a "packed" data format,using a structure that does not use any...
5
1978
by: Chris | last post by:
Hi I'm attempting to write a client for an existing p2p network. The protocol defines that ints are packed into 4 bytes for transfer. // Creating the byte vector using the following is fine: for(int i=3; i>=0; i--) { vecBuff.push_back(value&0xff); value/=256; }
9
1409
by: tkpmep | last post by:
I have a list y >>>y from which I want to extract only the 2nd and 4th item by partially unpacking the list. So I tried >>>a,b = y Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: list indices must be integers
11
1617
by: harold | last post by:
Dear all, Maybe I stared on the monitor for too long, because I cannot find the bug ... My script "transition_filter.py" starts with the following lines: import sys for line in sys.stdin : try :
16
1324
by: John Salerno | last post by:
I'm a little confused, but I'm sure this is something trivial. I'm confused about why this works: ('more', 'less'), ('something', 'nothing'), ('good', 'bad')) (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'), ('good', 'bad')) print x
5
1510
by: ram | last post by:
Stupid question #983098403: I can't seem to pass an unpacked sequence and keyword arguments to a function at the same time. What am I doing wrong? def f(*args, **kw): for a in args: print 'arg:', a for (k,v) in kw.iteritems(): print k, '=', v
3
1917
by: Chris Garland | last post by:
What's wrong here? I can unpack an unsigned char (144,) I can unpack a short (6,) But an unsigned char & a short give me this
0
7520
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7450
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7957
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7470
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3500
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1941
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1059
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.