473,799 Members | 2,935 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Best way to extract an item from a set of len 1

When you have a set, known to be of length one, is there a "best"
("most pythonic") way to retrieve that one item?

# given that I've got Python2.3.[45] on hand,
# hack the following two lines to get a "set" object
import sets
set = sets.Set s = set(['test'])
len(s) 1 s[0] Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unindexable object

(which is kinda expected, given that it's unordered...an index
doesn't make much sense)

To get the item, i had to resort to methods that feel less than
the elegance I've come to expect from python:
item = [x for x in s][0]
or the more convoluted two-step
item = s.pop()
s.add(item)
or even worse, intruding into private members
item = s._data.keys()[0]
Is any of these more "pythonic" than the others? Is there a more
elegant 2.3.x solution? If one upgrades to 2.4+, is there
something even more elegant? I suppose I was looking for
something like
item = s.aslist()[0]


which feels a little more pythonic (IMHO). Is one solution
preferred for speed over others (as this is happening in a fairly
deeply nested loop)?

Any tips, preferences, input, suggestions, pointers to obvious
things I've missed, or the like?

Thanks,

-tkc



Jan 25 '06 #1
8 1734
Tim Chase wrote:
When you have a set, known to be of length one, is there a "best"
("most pythonic") way to retrieve that one item?

s = set(["one-and-only"])
item, = s
item

'one-and-only'

This works for any iterable and guarantees that it contains exactly one
item. The comma may easily be missed, though.

Peter
Jan 25 '06 #2
That's cute. :-)

Fuzzyman

Jan 25 '06 #3
Tim Chase:
When you have a set, known to be of length one, is there a "best"
("most pythonic") way to retrieve that one item?


e = s.copy().pop() #:-)

--
René Pijlman

Wat wil jij worden? http://www.carrieretijger.nl
Jan 25 '06 #4
Tim Chase <py*********@ti m.thechases.com > wrote:
...
To get the item, i had to resort to methods that feel less than
the elegance I've come to expect from python:
>>> item = [x for x in s][0]

A shorter, clearer expression of the same idea:

item = list(s)[0]

or

item = list(s).pop()
or the more convoluted two-step
>>> item = s.pop()
>>> s.add(item)


which in turn suggests

item = set(s).pop()

Similar ideas include iter(s).next() and s.copy().pop().

Basically: s has no way to get the item non-destructively, so, either
make a copy (and use the destructive-get 'pop' on the copy) or build
from s a type which DOES have ways to get the item (iterator, list, etc)
be they destructive or not. As for speed, measuring is the only way,
and timeit is your friend. As for elegance, the most concise readable
form is "set(s).pop ()" and that's what I would use.
Alex
Jan 25 '06 #5
Peter Otten:
s = set(["one-and-only"])
item, = s
item
'one-and-only'

This works for any iterable and guarantees that it contains exactly one
item.


Nice!
The comma may easily be missed, though.


You could write:

(item,) = s

But I'm not sure if this introduces additional overhead.

--
René Pijlman

Wat wil jij worden? http://www.carrieretijger.nl
Jan 25 '06 #6
Peter Otten wrote:
When you have a set, known to be of length one, is there a "best"
("most pythonic") way to retrieve that one item?

s = set(["one-and-only"])
item, = s
item 'one-and-only'

This works for any iterable and guarantees that it contains exactly one
item. The comma may easily be missed, though.


you can make this a bit more obvious:
[item] = s


this is almost twice as fast as the fastest alternative from my previous
post.

</F>

Jan 25 '06 #7
Rene Pijlman <re************ ********@my.add ress.is.invalid > wrote:
Peter Otten:
> s = set(["one-and-only"])
> item, = s
...The comma may easily be missed, though.


You could write:

(item,) = s

But I'm not sure if this introduces additional overhead.


Naah...:

helen:~ alex$ python -mtimeit -s's=set([23])' 'x,=s'
1000000 loops, best of 3: 0.689 usec per loop
helen:~ alex$ python -mtimeit -s's=set([23])' '(x,)=s'
1000000 loops, best of 3: 0.652 usec per loop
helen:~ alex$ python -mtimeit -s's=set([23])' '[x]=s'
1000000 loops, best of 3: 0.651 usec per loop

....much of a muchness.
Alex
Jan 26 '06 #8
Alex Martelli wrote:
Rene Pijlman <re************ ********@my.add ress.is.invalid > wrote:
Peter Otten:
>>>> s = set(["one-and-only"])
>>>> item, = s ... >The comma may easily be missed, though.


You could write:

(item,) = s

But I'm not sure if this introduces additional overhead.


Naah...:

helen:~ alex$ python -mtimeit -s's=set([23])' 'x,=s'
1000000 loops, best of 3: 0.689 usec per loop
helen:~ alex$ python -mtimeit -s's=set([23])' '(x,)=s'
1000000 loops, best of 3: 0.652 usec per loop
helen:~ alex$ python -mtimeit -s's=set([23])' '[x]=s'
1000000 loops, best of 3: 0.651 usec per loop

...much of a muchness.


And that is no coincidence. All three variants are compiled to the same
bytecode:
import dis
def a(): x, = s .... def b(): (x,) = s .... def c(): [x] = s .... dis.dis(a) 1 0 LOAD_GLOBAL 0 (s)
3 UNPACK_SEQUENCE 1
6 STORE_FAST 0 (x)
9 LOAD_CONST 0 (None)
12 RETURN_VALUE dis.dis(b) 1 0 LOAD_GLOBAL 0 (s)
3 UNPACK_SEQUENCE 1
6 STORE_FAST 0 (x)
9 LOAD_CONST 0 (None)
12 RETURN_VALUE dis.dis(c)

1 0 LOAD_GLOBAL 0 (s)
3 UNPACK_SEQUENCE 1
6 STORE_FAST 0 (x)
9 LOAD_CONST 0 (None)
12 RETURN_VALUE

Peter

Jan 26 '06 #9

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

Similar topics

5
6918
by: Jane Doe | last post by:
Hi I took a quick look in the archives, but didn't find an answer to this one. I'd like to display a list of HTML files in a directory, showing the author's name between brackets after the file name. I can successfully extract the TITLE section, but no luck with the AUTHOR part. Any idea why?
4
1716
by: Harald Massa | last post by:
Old, very old informatical problem: I want to "print" grouped data with head information, that is: eingabe= shall give: ( Braces are not important...) 'Stuttgart', '70197' --data-- ('Fernsehturm', '20')
10
1980
by: Rich Wallace | last post by:
Hey all, I have an XML doc that I read into a SQL Server database from an integration feed.... ----------------XML snippet ---------------- <?xml version="1.0" encoding="us-ascii"?> <!--Product data from JDEdwards--> <Root> <Root RvcDate="2004-02-03" RcvTime="14.16.03.795135">
3
1886
by: Scott M. Lyon | last post by:
I'm trying to figure out the best way (considering there could be instances where I get a lot of data in this XML, and I want to minimize any slowdowns) to extract the value of one particular node from an XML string (not saved as a file, but passed as a string from another module). For example, let's assume I get back XML in a string that looks like this: <Commands> <cmd name="1">Value 1</cmd>
6
2807
by: mandibdc | last post by:
I need to extract some elements from a very large XML file. Because of the size, I'd like to work with it on my Linux machine as a text file. Basically, I am going to have a list of specific strings I'm searching for. For each string, I need to search through the XML file, and when I find that string (in the tag <code>), copy the entire <item> XML element that the code appears in, into another text file. The XML document is comprised...
5
5124
by: deko | last post by:
If I have random and unpredictable user agent strings containing URLs, what is the best way to extract the URL? For example, let's say the string looks like this: registered NYSE 943 <a href="http://netforex.net"Forex Trading Network Organization </ainfo@netforex.org What's the best way to extract http://netforex.net ?
8
2596
by: Guy | last post by:
Is there a better way to search identical elements in a sorted array list than the following: iIndex = Array.BinarySearch( m_Array, 0, m_Array.Count, aSearchedObject ); aFoundObject= m_Array; m_ResultArray.Add ( aFoundObject);
7
3387
by: SM | last post by:
Hello, I have an XML file that looks like this <?xml version="1.0" encoding="UTF-8"?> <discography> <CD> <title>Moonlight</title> <year>1974</year> <description>
1
2534
by: jeddiki | last post by:
I am using curl and DOMDocument to extract the links from my website. This is my script: require("my_functions.php"); $target_url = "http://www.support-focus.com/customer-service-software.html"; $userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
0
9688
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
9544
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
10490
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...
1
10238
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
10030
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
9077
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
5467
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5589
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.