473,732 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

list unpack trick?

I find that I use some list unpacking construct very often:

name, value = s.split('=',1)

So that 'a=1' unpack as name='a' and value='1' and 'a=b=c' unpack as
name='a' and value='b=c'.

The only issue is when s does not contain the character '=', let's say it
is 'xyz', the result list has a len of 1 and the unpacking would fail. Is
there some really handy trick to pack the result list into len of 2 so
that it unpack as name='xyz' and value=''?

So more generally, is there an easy way to pad a list into length of n
with filler items appended at the end?
Jul 18 '05 #1
6 2893
On Fri, Jan 21, 2005 at 08:02:38PM -0800, aurora wrote:
I find that I use some list unpacking construct very often:

name, value = s.split('=',1)

So that 'a=1' unpack as name='a' and value='1' and 'a=b=c' unpack as
name='a' and value='b=c'.

The only issue is when s does not contain the character '=', let's say it
is 'xyz', the result list has a len of 1 and the unpacking would fail. Is
there some really handy trick to pack the result list into len of 2 so
that it unpack as name='xyz' and value=''?


what about:
s.find( '=' )!=-1 and s.split( '=', 1 ) or [s,'']

bye bye - sifu
Jul 18 '05 #2
"aurora" wrote:
The only issue is when s does not contain the character '=', let's say it is 'xyz', the result
list has a len of 1 and the unpacking would fail. Is there some really handy trick to pack the
result list into len of 2 so that it unpack as name='xyz' and value=''?
do you need a trick? spelling it out works just fine:

try:
key, value = field.split("=" , 1)
except:
key = field; value = ""

or

if "=" in field:
key, value = field.split("=" , 1)
else:
key = field; value = ""

(the former might be slightly more efficient if the "="-less case is uncommon)

or, if you insist:

key, value = re.match("([^=]*)(?:=(.*))?", field).groups()

or

key, value = (field + "="["=" in field:]).split("=", 1)

but that's not really worth the typing. better do

key, value = splitfield(fiel d)

with a reasonable definition of splitfield (I recommend the try-except form).
So more generally, is there an easy way to pad a list into length of n with filler items appended
at the end?


some variants (with varying semantics):

list = (list + n*[item])[:n]

or

list += (n - len(list)) * [item]

or (readable):

if len(list) < n:
list.extend((n - len(list)) * [item])

etc.

</F>

Jul 18 '05 #3
Fredrik Lundh <fr*****@python ware.com> wrote:
...
or (readable):

if len(list) < n:
list.extend((n - len(list)) * [item])


I find it just as readable without the redundant if guard -- just:

alist.extend((n - len(alist)) * [item])

of course, this guard-less version depends on N*[x] being the empty list
when N<=0, but AFAIK that's always been the case in Python (and has
always struck me as a nicely intuitive semantics for that * operator).

itertools-lovers may prefer:

alist.extend(it ertools.repeat( item, n-len(alist)))

a bit less concise but nice in its own way (itertools.repe at gives an
empty iterator when its 2nd argument is <=0, of course).
Alex
Jul 18 '05 #4
Alex Martelli wrote:
or (readable):

if len(list) < n:
list.extend((n - len(list)) * [item])


I find it just as readable without the redundant if guard -- just:

alist.extend((n - len(alist)) * [item])


the guard makes it obvious what's going on, also for a reader that doesn't
know exactly how "*" behaves for negative counts. once you've seen the
"compare length to limit" and "extend", you don't have to parse the rest of
the statement.

</F>

Jul 18 '05 #5
Fredrik Lundh <fr*****@python ware.com> wrote:
Alex Martelli wrote:
or (readable):

if len(list) < n:
list.extend((n - len(list)) * [item])
I find it just as readable without the redundant if guard -- just:

alist.extend((n - len(alist)) * [item])


the guard makes it obvious what's going on, also for a reader that doesn't
know exactly how "*" behaves for negative counts.


It does, but it's still redundant, like, say,
if x < 0:
x = abs(x)
makes things obvious even for a reader not knowing exactly how abs
behaves for positive arguments. Redundancy in the code to try and
compensate for a reader's lack of Python knowledge is not, IMHO, a
generally very productive strategy. I understand perfectly well that
you and others may disagree, but I just thought it worth stating my
personal opinion in the matter.
once you've seen the
"compare length to limit" and "extend", you don't have to parse the rest of
the statement.


Sorry, I don't get this -- it seems to me that I _do_ still have to
"parse the rest of the statement" to understand exactly what alist is
being extended by.
Alex
Jul 18 '05 #6
Thanks. I'm just trying to see if there is some concise syntax available
without getting into obscurity. As for my purpose Siegmund's suggestion
works quite well.

The few forms you have suggested works. But as they refer to list multiple
times, it need a separate assignment statement like

list = s.split('=',1)

I am think more in the line of string.ljust(). So if we have a
list.ljust(leng th, filler), we can do something like

name, value = s.split('=',1). ljust(2,'')

I can always break it down into multiple lines. The good thing about list
unpacking is its a really compact and obvious syntax.

On Sat, 22 Jan 2005 08:34:27 +0100, Fredrik Lundh <fr*****@python ware.com>
wrote:
....
So more generally, is there an easy way to pad a list into length of n
with filler items appended
at the end?


some variants (with varying semantics):

list = (list + n*[item])[:n]

or

list += (n - len(list)) * [item]

or (readable):

if len(list) < n:
list.extend((n - len(list)) * [item])

etc.

</F>

Jul 18 '05 #7

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

Similar topics

2
4883
by: Raoul | last post by:
I wrote a COM server object in C++ a few months ago. I can use it from Visual Basic, Visual C++, S-Plus and a number of other scripting environments. What I can't do is use it with my FAVOURITE scripting language, Python. I have tried everything by I'm going crazy here. Here is what I have...
5
13848
by: Geoffrey | last post by:
Hope someone can help. I am trying to read data from a file binary file and then unpack the data into python variables. Some of the data is store like this; xbuffer: '\x00\x00\xb9\x02\x13EXCLUDE_CREDIT_CARD' # the above was printed using repr(xbuffer). # Note that int(0x13) = 19 which is exactly the length of the visible text #
20
2233
by: Lucas Raab | last post by:
I'm done porting the C code, but now when running the script I continually run into problems with lists. I tried appending and extending the lists, but with no avail. Any help is much appreciated Please see both the Python and C code at http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py TIA
5
5455
by: grant | last post by:
Hi All, I am pretty new to python and am having a problem intepreting binary data using struct.unpack. I am reading a file containing binary packed data using open with "rb". All the values are coming through fine when using (integer1,) = struct.unpack('l', line) except when line contains "carriage-return" "linefeed" which are valid binary packed values. Error = unpack string size dows not match format. It seems that
14
12277
by: Richard | last post by:
I have a large list of two element tuples. I want two separate lists: One list with the first element of every tuple, and the second list with the second element of every tuple. Each tuple contains a datetime object followed by an integer. Here is a small sample of the original list: ((datetime.datetime(2005, 7, 13, 16, 0, 54), 315), (datetime.datetime(2005, 7, 13, 16, 6, 12), 313),
3
1806
by: Nx | last post by:
Is there a better solution to following problem : I want to unpack a list into variables the list is created at runtime and I do not know how many items there will be , but I know not more than 25. The list unpacks into variables which are prev. defined as line1,line2....line25 which are actually the names of lineedit fields in a Qt gui application and which need to be populated. I currently use following to achieve that :
1
1383
by: Panos Laganakos | last post by:
Is there some other practice than reading all the strings and slicing them later? They're stored in the form of: List Group: char name; So I thought of doing: unpacked = unpack('%s' % (10*17), data)
4
2800
by: OhKyu Yoon | last post by:
Hi! I have a really long binary file that I want to read. The way I am doing it now is: for i in xrange(N): # N is about 10,000,000 time = struct.unpack('=HHHH', infile.read(8)) # do something tdc = struct.unpack('=LiLiLiLi',self.lmf.read(32)) # do something
6
2926
by: Shawn Minisall | last post by:
I'm writing a game that uses two functions to check and see if a file called highScoresList.txt exists in the main dir of the game program. If it doesn, it creates one. That part is working fine. The problem is arising when it goes to read in the high scores from the file when I play again. This is the error msg python is giving me Traceback (most recent call last): File "<pyshell#0>", line 1, in <module>
0
8946
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8774
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9447
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9307
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9235
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9181
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.