473,770 Members | 1,661 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

defining the behavior of zip(it, it) (WAS: Converting a flat list...)

[Duncan Booth]
aList = ['a', 1, 'b', 2, 'c', 3]
it = iter(aList)
zip(it, it)
[('a', 1), ('b', 2), ('c', 3)]


[Alan Isaac] That behavior is currently an accident.
http://sourceforge.net/tracker/?grou...il&aid=1121416
[Bengt Richter] That says
"""
ii. The other problem is easier to explain by example.
Let it=iter([1,2,3,4]).
What is the result of zip(*[it]*2)?
The current answer is: [(1,2),(3,4)],
but it is impossible to determine this from the docs,
which would allow [(1,3),(2,4)] instead (or indeed
other possibilities).
"""
IMO left->right is useful enough to warrant making it defined
behaviour


And in fact, it is defined behavior for itertools.izip( ) [1].

I don't see why it's such a big deal to make it defined behavior for
zip() too.

STeVe

[1]http://docs.python.org/lib/itertools-functions.html# l2h-1392
Nov 22 '05
38 2110
ru***@yahoo.com wrote:
led to more serious flaws like the missing if-then-else expression,
something I use in virtually every piece of code I write, and which
increases readability.
you obviously need to learn more Python idioms. Python works better
if you use it to write Python code; not when you mechanically translate
stuff written in other languages to Python.
(Well, ok that is not the end of the world either but it's lack is irritating
as hell, and yes, I know that it is now back in favor.)


the thing that's in favour is "then-if-else", not "if-then-else".

</F>

Nov 23 '05 #11

Fredrik Lundh wrote:
(Well, ok that is not the end of the world either but it's lack is irritating
as hell, and yes, I know that it is now back in favor.)


the thing that's in favour is "then-if-else", not "if-then-else".

there it comes :-)

Nov 23 '05 #12
Op 2005-11-23, Fredrik Lundh schreef <fr*****@python ware.com>:
ru***@yahoo.com wrote:
led to more serious flaws like the missing if-then-else expression,
something I use in virtually every piece of code I write, and which
increases readability.


you obviously need to learn more Python idioms. Python works better
if you use it to write Python code; not when you mechanically translate
stuff written in other languages to Python.


What does this mean?

It could mean that python works better with those concepts that are
already implemented in python. That seems obvious, but isn't
an argument for or against implementing a particular language
feature.

It could also mean that some language feature will never work well
in python even when implemented. Are you arguing that a conditional
expression is such a feature?
(Well, ok that is not the end of the world either but it's lack is irritating
as hell, and yes, I know that it is now back in favor.)


the thing that's in favour is "then-if-else", not "if-then-else".


Well I don't know about the previous poster, but I'm mostly interesseted
in a conditional expression. Whether it is "then-if-else" or "if-then-else"
seems less important to me.

--
Antoon Pardon
Nov 23 '05 #13
On Tue, 22 Nov 2005 23:17:31 -0700 in comp.lang.pytho n, Steven Bethard
<st************ @gmail.com> wrote:
rh********@gma il.com wrote:

[...]
IIRC, this was discussednd rejected in an SF bug report. It should not
be a defined behavior for severals reasons:

[snip arguments about how confusing zip(it, it) is]
Overall, I think anyone using zip(it,it) is living in a state of sin,
drawn to the tempations of one-liners and premature optimization. They
are forsaking obvious code in favor of screwy special cases. The
behavior has been left undefined for a reason.


Then why document itertools.izip( ) as it is? The documentation there is
explicit enough to know that izip(it, it) will work as intended. Should
we make the documentation there less explicit to discourage people from
using the izip(it, it) idiom?


ISTM that one would use itertools.izip in order to get some
functionality not available from zip. Perhaps this is one of those
bits of functionality.

But I admit, I'm not all that familiar with itertools...

In any case, the solution seems obvious: if you want the guarantee,
use the tool that provides it.

Regards,
-=Dave

--
Change is inevitable, progress is not.
Nov 23 '05 #14
[Steven Bethard]
Then why document itertools.izip( ) as it is? The documentation there is
explicit enough to know that izip(it, it) will work as intended. Should
we make the documentation there less explicit to discourage people from
using the izip(it, it) idiom?

[Dave Hansen] In any case, the solution seems obvious: if you want the guarantee,
use the tool that provides it.


True enough :-)

FWIW, the itertools documentation style was intended more as a learning
device than as a specification. I combined regular documentation,
approximately equivalent generator code, examples, and recipes.
Hopefully, reading the module docs creates an understanding of what the
tools do, how to use them, how to combine them, and how to roll your
own to extend the toolset. Another goal was providing code fragments
to support scripts needing to run on Py2.2 (itertools were introduced
in Py2.3).
Raymond

Nov 23 '05 #15
Steven Bethard wrote:
Then why document itertools.izip( ) as it is? The documentation there is
explicit enough to know that izip(it, it) will work as intended. Should
we make the documentation there less explicit to discourage people from
using the izip(it, it) idiom?


depends on whether you interpret "equivalent " as "having similar effects"
or "correspond ing or virtually identical especially in effect or function" or
if you prefer some other dictionary definition...

because there are of course plenty of subtle differences between a Python
generator C type implementation. let's see...
from itertools import izip as izip1
from library documentation import izip as izip2 izip1 <type 'itertools.izip '> izip2 <function izip2 at 0x00A26670>

alright, close enough.
izip1.func_name Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: type object 'itertools.izip ' has no attribute 'func_name' izip2.func_name 'izip'

hmm.
class myiter: .... def next(self):
.... raise ValueError("oop s!")
.... izip2(myiter()) <generator object at 0x00A2AB48> izip1(myiter()) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: izip argument #1 must support iteration

oops.
class myiter: .... def __iter__(self):
.... return self
.... def next(self):
.... raise ValueError("oop s!")
.... izip1(myiter()) <itertools.iz ip object at 0x00A2AC88> izip2(myiter()) <generator object at 0x00A2AB48>

that's better. now let's run it:
list(izip1(myit er())) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in next
ValueError: oops! list(izip2(myit er()))

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "i.py", line 6, in izip2
result = [i.next() for i in iterables]
File "<stdin>", line 5, in next
ValueError: oops!

different stack depths. hmm.

so how equivalent must something be to be equivalent?

</F>

Nov 23 '05 #16
yet another :-)

Fredrik Lundh wrote:
Steven Bethard wrote:
Then why document itertools.izip( ) as it is? The documentation there is
explicit enough to know that izip(it, it) will work as intended. Should
we make the documentation there less explicit to discourage people from
using the izip(it, it) idiom?


depends on whether you interpret "equivalent " as "having similar effects"
or "correspond ing or virtually identical especially in effect or function" or
if you prefer some other dictionary definition...

because there are of course plenty of subtle differences between a Python
generator C type implementation. let's see...
from itertools import izip as izip1
from library documentation import izip as izip2 izip1 <type 'itertools.izip '> izip2 <function izip2 at 0x00A26670>

alright, close enough.
izip1.func_name Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: type object 'itertools.izip ' has no attribute 'func_name' izip2.func_name 'izip'

hmm.
class myiter: ... def next(self):
... raise ValueError("oop s!")
... izip2(myiter()) <generator object at 0x00A2AB48> izip1(myiter()) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: izip argument #1 must support iteration

oops.
class myiter: ... def __iter__(self):
... return self
... def next(self):
... raise ValueError("oop s!")
... izip1(myiter()) <itertools.iz ip object at 0x00A2AC88> izip2(myiter()) <generator object at 0x00A2AB48>

that's better. now let's run it:
list(izip1(myit er())) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in next
ValueError: oops! list(izip2(myit er()))

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "i.py", line 6, in izip2
result = [i.next() for i in iterables]
File "<stdin>", line 5, in next
ValueError: oops!

different stack depths. hmm.

so how equivalent must something be to be equivalent?

</F>


Nov 23 '05 #17
bo****@gmail.co m wrote:
Steven Bethard wrote:
rh********@gm ail.com wrote:
>ii. The other problem is easier to explain by example.
>Let it=iter([1,2,3,4]).
>What is the result of zip(*[it]*2)?
>The current answer is: [(1,2),(3,4)],
>but it is impossible to determine this from the docs,
>which would allow [(1,3),(2,4)] instead (or indeed
>other possibilities).
>"""
>IMO left->right is useful enough to warrant making it defined
>behaviou r

And in fact, it is defined behavior for itertools.izip( ) [1].

I don't see why it's such a big deal to make it defined behavior for
zip() too.
IIRC, this was discussednd rejected in an SF bug report. It should not
be a defined behavior for severals reasons:
[snip arguments about how confusing zip(it, it) is]
Overall, I think anyone using zip(it,it) is living in a state of sin,
drawn to the tempations of one-liners and premature optimization. They
are forsaking obvious code in favor of screwy special cases. The
behavior has been left undefined for a reason.


Then why document itertools.izip( ) as it is? The documentation there is
explicit enough to know that izip(it, it) will work as intended. Should
we make the documentation there less explicit to discourage people from
using the izip(it, it) idiom?

[snip]
But technically speaking, you are still referring to the implementation
detail of izip(), not the functionality of izip().

I do now agree with another poster that the documentation of both zip
and izip should state clear that the order of picking from which
iterable is undefined or can be changed from implementation to
implementation, to avoid this kind of temptation.


Actually, it's part of the specificiation. Read the itertools
documentation[1]:

"""
izip(*iterables )
Make an iterator that aggregates elements from each of the
iterables. Like zip() except that it returns an iterator instead of a
list. Used for lock-step iteration over several iterables at a time.
Equivalent to:

def izip(*iterables ):
iterables = map(iter, iterables)
while iterables:
result = [i.next() for i in iterables]
yield tuple(result)
"""

So technically, since itertools.izip( ) is "equivalent to" the Python
code above, it is part of the specification, not the implementation.

But I certainly understand Raymond's point -- the code in the itertools
documentation there serves a number of purposes other than just
documenting the behavior.

[1]http://docs.python.org/lib/itertools-functions.html# l2h-1392

STeVe
Nov 23 '05 #18
rh********@gmai l.com wrote:
[Dave Hansen]
In any case, the solution seems obvious: if you want the guarantee,
use the tool that provides it.


True enough :-)

FWIW, the itertools documentation style was intended more as a learning
device than as a specification. I combined regular documentation,
approximately equivalent generator code, examples, and recipes.
Hopefully, reading the module docs creates an understanding of what the
tools do, how to use them, how to combine them, and how to roll your
own to extend the toolset.


maybe it's time to change "equivalent to" to "similar to", to avoid
messing things up for people who reads the mostly informal library
reference as if it were an ISO specification.

</F>

Nov 23 '05 #19
> > FWIW, the itertools documentation style was intended more as a learning
device than as a specification. I combined regular documentation,
approximately equivalent generator code, examples, and recipes.
Hopefully, reading the module docs creates an understanding of what the
tools do, how to use them, how to combine them, and how to roll your
own to extend the toolset.

[Fredrik Lundh] maybe it's time to change "equivalent to" to "similar to", to avoid
messing things up for people who reads the mostly informal library
reference as if it were an ISO specification.


Will do.

This is doubly a good idea because there are small differences in
argument processing. For example, count() makes an immediate check for
a numerical argument but the generator version won't recognize the
fault until the count(x).next() is called.

Nov 23 '05 #20

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

Similar topics

23
3214
by: Ken Turkowski | last post by:
The construct (void*)(((long)ptr + 3) & ~3) worked well until now to enforce alignment of the pointer to long boundaries. However, now VC++ warns about it, undoubtedly to help things work on 64 bit machines, i.e. with 64 bit pointers. In the early days of C, where there were problems with the size of int being 16 or 32 bits, the response was that an int was guaranteed to hold a pointer (yes, there were 64Kb address spaces at one time!)....
31
2355
by: metiu uitem | last post by:
Say you have a flat list: How do you efficiently get , , ] I was thinking of something along the lines of: for (key,number) in list: print key, number
12
2617
by: dav3 | last post by:
Hi again folks. I have a function called "linearRegression()" now I am along way from finishing this function atm. A little about this function: The function executes an SQL query grabbing a column from a table in my database called "Yahoo". Now here is where things are getting fuzzy for me. I need to be able to perform mathematical operations on this result set ie. finding the rsquared value, slope, average etc..... but i cannot do any of this...
11
1579
by: Louis.Soninhu | last post by:
Hi pals I have a list like this mylist= I'd like to remove the first and the last item as they are irrevalent, and convert it to the dict: {'tom':'boss','mike':'manager','paul':'employee'}
9
3136
by: victory2006 | last post by:
I need help converting a list into a string ex/ i want to compare this, "110"(string) to this (list) to see if they are identical. So, how would you do this? convert the string into a list? the list into a string? then compare the two? thanks in advance
0
9595
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
9432
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
10232
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
9873
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
8891
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
6682
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
5313
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...
2
3578
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2822
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.