473,804 Members | 3,043 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Are tuple really immutable?

Hi

Consider the following tuples:
t = ([1],[2])
u = (1,2)
v = ('1','2')
t ([1], [2]) u (1, 2) v ('1', '2') t.__hash__() Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list objects are unhashable u.__hash__() 219750523 v.__hash__() -1786881095 d = dict()
d[t] = 't' Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list objects are unhashable d[u] = 'u'
d[v] = 'v'
d {('1', '2'): 'v', (1, 2): 'u'}

t, u and v are all tuples. t and v elements are sequences.
Yet, t cannot be a dictionnary key because its elements are mutable.

1) Given a tuple, how can I know if it can be a dictionnary key or not?

Of course I could call __hash__ and catch for a TypeError exception,
but I'm looking for a better way to do it.

2) Would it be possible to have a "ismutable" function or method? Like: t.ismutable() True, well maybe not... u.ismutable() False u.ismutable() False

3) In this example, is t considered mutable or not?
"Tuple are immutable" says the doc, but: t[0].append(0)
t ([1, 0], [2])

The tuple is immutable but its elements can be mutable: I tend to think
that it means that the tuple is mutable. Indeed, it changed!

4) Even more confusing: I had the following strange result:
(with both Python 2.3.3 and 2.4) t[0]+=[1] Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment t

([1, 0, 1], [2])
There was an exception, but the list was still changed!?

Chris

Jul 18 '05 #1
5 1688

"Chris" <ch**********@g mail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Hi
3) In this example, is t considered mutable or not?
"Tuple are immutable" says the doc, but:
t[0].append(0)
t ([1, 0], [2])

The tuple is immutable but its elements can be mutable: I tend to think
that it means that the tuple is mutable. Indeed, it changed!
Well, it did and it didn't. If you went in and did an
id() on each element, you'd discover that the actual
objects didn't change: the exact same ids were in
the exact same slots before and after. What you're
seeing is the way the str() and repr() functions print
the values of embedded objects, not the ids.

4) Even more confusing: I had the following strange result:
(with both Python 2.3.3 and 2.4) t[0]+=[1] Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment t
([1, 0, 1], [2])
There was an exception, but the list was still changed!?


I consider that an error, but I've had several people
tell me that it's the way it's supposed to be.
I simply quit trying to get the point across.
As far as I'm concerned, the behavior is simply
wrong. Since mutating the object didn't change
the id, it shouldn't try to replace the object in
the tuple.

John Roth
Chris


Jul 18 '05 #2
"Chris" wrote:
1) Given a tuple, how can I know if it can be a dictionnary key or not?

Of course I could call __hash__ and catch for a TypeError exception,
but I'm looking for a better way to do it.
calling hash(obj) is the only sane way to figure out if calling hash(obj)
will work.
2) Would it be possible to have a "ismutable" function or method?
objects are mutable only if they have some method (visible or __hidden__)
that can be used to modify their contents. from the Python runtime perspec-
tive, objects are objects.
3) In this example, is t considered mutable or not?
"Tuple are immutable" says the doc, but:
t[0].append(0)
t ([1, 0], [2])

The tuple is immutable but its elements can be mutable: I tend to think
that it means that the tuple is mutable. Indeed, it changed!
as map(id, t) can tell you, the tuple object itself wasn't modified.
4) Even more confusing: I had the following strange result:
(with both Python 2.3.3 and 2.4) t[0]+=[1] Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment t

([1, 0, 1], [2])
There was an exception, but the list was still changed!?


that's a silly side-effect of how "+=" is defined for lists; the "+" part of the
expression works, and modifies the target object, but the "=" part fails.

</F>

Jul 18 '05 #3
Chris <ch**********@g mail.com> wrote:
...
3) In this example, is t considered mutable or not?
"Tuple are immutable" says the doc, but:
t[0].append(0)
t

([1, 0], [2])

The tuple is immutable but its elements can be mutable: I tend to think
that it means that the tuple is mutable. Indeed, it changed!


Maybe the last page of
<http://mail.python.org/pipermail/python-list/2002-April/099227.html>
can help with this conceptual issue.
Alex
Jul 18 '05 #4
Chris <ch**********@g mail.com> wrote:
...
3) In this example, is t considered mutable or not?
"Tuple are immutable" says the doc, but:
>>> t[0].append(0)
>>> t

([1, 0], [2])

The tuple is immutable but its elements can be mutable: I tend to think
that it means that the tuple is mutable. Indeed, it changed!


No, not in the way intended by the word 'mutable'. A tuple is like an
ordered club roster written in indelible ink before the time of whiteout.
The members of the club may change (change jobs, residence, relationships,
etc) but the roster remains the same: same members, same ranking.

Terry J. Reedy

Jul 18 '05 #5
I'm suing Google Groups (beta) which has a treeview and my thanks were
a reply to Fredrik Lundh. In fact I simply clicked a "reply" link below
his post.
Of course you all helped me to better understand the
"mutable/immutable" concept but Fredrik Lundh deserves more thanks
since he replied to all my questions ;-)

Chris

Jul 18 '05 #6

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

Similar topics

10
5223
by: Carlo v. Dango | last post by:
Hello there. I have a function which as an argument takes a tuple and either returns that tuple or a mutated version of it. The problem is that tuples are imutable, hence I have to create a new tuple and copy the content of the old tuple to a new one. But how do I do this if I only at runtime know the size of the tuple? I wish I could pass around lists instead.. that would be so much easier, but I'm passing "*args" and "**kwargs" around...
9
4082
by: Yomanium Yoth Taripoät II | last post by:
HI, 1) what are the differences between list and tuple? 2) how to concatenate tuple and list? no method, no opérator? 3) im looking the fucking manual, and cant add value in my tuple, when it already created :/ how to do it? thx.
50
3698
by: Will McGugan | last post by:
Hi, Why is that a tuple doesnt have the methods 'count' and 'index'? It seems they could be present on a immutable object. I realise its easy enough to convert the tuple to a list and do this, I'm just curious why it is neccesary.. Thanks,
37
2396
by: Gregor Horvath | last post by:
Hi, >>>type() <type 'list'> >>>type(('1')) <type 'str'> I wonder why ('1') is no tuple????
43
3387
by: Tim Chase | last post by:
Just as a pedantic exercise to try and understand Python a bit better, I decided to try to make a generator or class that would allow me to unpack an arbitrary number of calculatible values. In this case, just zeros (though I just to prove whatever ends up working, having a counting generator would be nice). The target syntax would be something like >>> a,b,c = zeros() >>> q,r,s,t,u,v = zeros()
77
4470
by: Nick Maclaren | last post by:
Why doesn't the tuple type have an index method? It seems such a bizarre restriction that there must be some reason for it. Yes, I know it's a fairly rare requirement. Regards, Nick Maclaren.
2
3488
by: Alan Isaac | last post by:
I am probably confused about immutable types. But for now my questions boil down to these two: - what does ``tuple.__init__`` do? - what is the signature of ``tuple.__init__``? These questions are stimulated by http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303439 Looking at that, what fails if I leave out the following line? ::
7
4447
by: Shafik | last post by:
Hello folks, I am an experienced programmer, but very new to python (2 days). I wanted to ask: what exactly is the difference between a tuple and a list? I'm sure there are some, but I can't seem to find a situation where I can use one but not the other. Thanks in advance, --Shafik
2
6036
by: hall.jeff | last post by:
Before the inevitable response comes, let me assure you I've read through the posts from Guido about this. 7 years ago Guido clearly expressed a displeasure with allowing these methods for tuple. Let me lay out (in a fresh way) why I think we should reconsider. 1) It's counterintuitive to exclude them: It makes very little sense why an indexable data structure wouldn't have .index() as a method. It makes even less sense to not allow...
0
9706
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
9579
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
10571
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
10326
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
10317
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
10075
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
5520
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
3815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2990
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.