473,835 Members | 1,734 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

about sort and dictionary

Got confused by the following code:
a [6, 3, 1] b [4, 3, 1] c {1: [[6, 3, 1], [4, 3, 1]], 2: [[6, 3, 1]]} c[2].append(b.sort( ))
c {1: [[6, 3, 1], [1, 3, 4]], 2: [[6, 3, 1], None]}
#why c can not append the sorted b?? b.sort()
b

[1, 3, 4]
Nov 22 '05 #1
99 4700

Shi Mu wrote:
Got confused by the following code:
a [6, 3, 1] b [4, 3, 1] c {1: [[6, 3, 1], [4, 3, 1]], 2: [[6, 3, 1]]} c[2].append(b.sort( ))
c {1: [[6, 3, 1], [1, 3, 4]], 2: [[6, 3, 1], None]}
#why c can not append the sorted b?? b.sort()
b

[1, 3, 4]

most built-in function/method don't return the "object" but None. This
I believe is the language creator's preference for everything being
explicit. You better do it like this :

b.sort()
c[2].append(b)

Of course, this make things like this not possible :

obj.method_a(). method_b().meth od_c()

But the language(and the community) in general discourage you to write
code like this ;-)

Nov 22 '05 #2

Shi Mu wrote:
Got confused by the following code:
a [6, 3, 1] b [4, 3, 1] c {1: [[6, 3, 1], [4, 3, 1]], 2: [[6, 3, 1]]} c[2].append(b.sort( ))
c {1: [[6, 3, 1], [1, 3, 4]], 2: [[6, 3, 1], None]}
#why c can not append the sorted b?? b.sort()
b

[1, 3, 4]

most built-in function/method don't return the "object" but None. This
I believe is the language creator's preference for everything being
explicit. You better do it like this :

b.sort()
c[2].append(b)

Of course, this make things like this not possible :

obj.method_a(). method_b().meth od_c()

But the language(and the community) in general discourage you to write
code like this ;-)

Nov 22 '05 #3
Shi Mu <sa************ @gmail.com> writes:
#why c can not append the sorted b??


Because sort() doesn't return anything?

According to the library reference:

7) The sort() and reverse() methods modify the list in place for
economy of space when sorting or reversing a large list. To remind you
that they operate by side effect, they don't return the sorted or
reversed list.
--
Eric Jacoboni, ne il y a 1435934131 secondes
Nov 22 '05 #4
Shi Mu <sa************ @gmail.com> writes:
#why c can not append the sorted b??


Because sort() doesn't return anything?

According to the library reference:

7) The sort() and reverse() methods modify the list in place for
economy of space when sorting or reversing a large list. To remind you
that they operate by side effect, they don't return the sorted or
reversed list.
--
Eric Jacoboni, ne il y a 1435934131 secondes
Nov 22 '05 #5
Magnus Lycka wrote:
Actually, I guess it's possible that sorted() is done so
that it works like below, but I don't think pre-sorted()
versions of Python support keyword arguments to list.sort()
anyway...

def sorted(l, *p, **kw): s=l[:];s.sort(*p, **kw);return s


One part you missed, sorted is actually closer to:

def sorted(iterable , cmp=None, key=None, reverse=False):
"sorted(iterabl e, cmp=None, key=None, reverse=False) --> new sorted list"
s=list(iterable )
s.sort(cmp, key, reverse)
return s

The point being that while in general only a list will have a sort
method, the sorted builtin may be called on any iterable and will
return a sorted list.

Also note that it only accepts specific named arguments, and has a
docstring.
Nov 22 '05 #6

Magnus Lycka wrote:
sorted_l = l.sort()

and while sorted_l would contain what one might expect, it
would in fact just be another name referencing exactly the
same sorted list as l, and it would probably be surprising
that l was also sorted, and that subsequent changes would
show up in both sorted_l and l, and that sorted_l might not
be sorted and longer even though you only modified l. It's
this particular gotcha that the language creator wanted to
avoid.

Since python's '=' is just name binding and that most objects(other
than those like int/float/string?) are mutable, I don't quite
understand why this is a gotcha that is so worrying.

a = [1,2,3]
a.sorted()
b = a

even an entry level python programmer can't expect 'b' to be
unchanged(after getting the first bite may be) if there is any
operation on a later. This not only applies to list but almost all
mutable object.

As you said, if one wants a copy of an object, use copy/deepcopy or
even pickle to get a snapshot of it.

Nov 22 '05 #7
bo****@gmail.co m wrote:
Since python's '=' is just name binding and that most objects(other
than those like int/float/string?) are mutable, I don't quite
understand why this is a gotcha that is so worrying.

a = [1,2,3]
a.sorted()
b = a

even an entry level python programmer can't expect 'b' to be
unchanged(after getting the first bite may be) if there is any
operation on a later. This not only applies to list but almost all
mutable object.


so what would an entry-level Python programmer expect from this
piece of code?

for item in a.reverse():
print item
for item in a.reverse():
print item

(as the X people used to say, the only thing worse than generalizing
from one example (sort) is generalizing from no examples at all ("let's
assume I have a use case")).

</F>

Nov 22 '05 #8

Fredrik Lundh wrote:
so what would an entry-level Python programmer expect from this
piece of code?

for item in a.reverse():
print item
for item in a.reverse():
print item

I would expect it to first print a in reverse then a as it was.

a=[1,2,3]

I expect it to print

3
2
1
1
2
3

As for your other comment, I don't even understand them.

Nov 22 '05 #9
bo****@gmail.co m wrote:
so what would an entry-level Python programmer expect from this
piece of code?

for item in a.reverse():
print item
for item in a.reverse():
print item

I would expect it to first print a in reverse then a as it was.

a=[1,2,3]

I expect it to print

3
2
1
1
2
3


really? wouldn't

3
2
1
3
2
1

make a lot more sense ?

</F>

Nov 22 '05 #10

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

Similar topics

4
1717
by: Raymond Arthur St. Marie II of III | last post by:
very Very VERY dumb ? about the new Set( ) 's Please be kind and read this like you know I've been up 33-34 hours reading PEP's but... Doc\ref 2.6 Delimiters show's three unused characters "@ $ ?". @ sort of looks like and sort of sounds like a set an $ well sort of obvious. I can imagine that the $ would be confused for money and @ is ugly.
39
3191
by: Marco Aschwanden | last post by:
Hi I don't have to talk about the beauty of Python and its clear and readable syntax... but there are a few things that striked me while learning Python. I have collected those thoughts. I am sure there are many discussions on the "problems" mentioned here. But I had this thoughts without looking into any forums or anything... it is kind of feedback.
22
1776
by: lechequier | last post by:
Let's say I define a list of pairs as follows: >>l = Can anyone explain why this does not work? >>h = {}.update(l) and instead I have to go: >>h = {} >>h.update(l) to initialize a dictionary with the given list of pairs?
90
3485
by: John Salerno | last post by:
I'm a little confused. Why doesn't s evaluate to True in the first part, but it does in the second? Is the first statement something different? False print 'hi' hi Thanks.
3
1295
by: erik gartz | last post by:
Hello, I'm new to python and I'm having difficulty understanding the following code. Why doesn't the variable a contain , ] instead. Doesn't {} allocate new memory for the dictionary each time? It almost appears as if the 2nd dictionary created overwrites the first one. Thanks for your help, Erik , ] a = {'x':i} , ]
1
2609
by: hn.ft.pris | last post by:
"Forward maximum match" mean that there is a dictionary contains thousands of items which are single words. For example, "kid", "nice", "best"... And here get a string "kidnicebs", the forward maximum match algorithm need to find the longest string that matches the string in dictionary. Because the longest string in the dictionary has a length of 4, so the algoritm pick the first four characters of the string(that's why it's called...
5
2616
by: Neil Chambers | last post by:
Hi All, I'm looking to see if it's feasible to use the SortObjectCommand included in the Microsoft.Powershell.Commands assembly. I have a Dictionary Dictionary<string, intd = new Dictionary<string, int>(); d = new int;
2
2846
by: kdt | last post by:
Hi, I need to perform some horrible functions in python I need to do, using sort in a similar way that Excel can. With a dictionary like: >>> d {8: (99, 99), 9: , 4: , 5: (67, 77)} I want to sort the entire dictionary based on the last values in each line. First for and then.
37
2201
by: Hilton | last post by:
Hi, for (int i = 0; i < list.Count; i++) has a hidden performance hit; i.e. list.Count gets evaluated each time, so we write something like: int listCount = list.Count; for (int i = 0; i < listCount; i++)
0
9800
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
9651
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
10802
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
10225
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
9340
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
6961
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
5630
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
5802
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3987
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.