473,563 Members | 2,884 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

length of a tuple or a list containing only one element

TP
Hi everybody,

I have a question about the difference of behavior of "len" when applied on
tuples or on lists. I mean:

$ len( ( 'foo', 'bar' ) )
2
$ len( ( 'foo' ) )
3
$ len( [ 'foo', 'bar' ] )
2
$ len( [ 'foo' ] )
1

Why this behavior for the length computation of a tuple?
For my application, I prefer the behavior of length for a list. If I want to
store some values in a tuple because they should not be modified, the case
where the tuple contains only one element bothers me.

Thanks

Julien
--
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+ ,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
Nov 3 '08 #1
10 1499
On Nov 3, 9:08*pm, TP <Tribulati...@P aralleles.inval idwrote:
I have a question about the difference of behavior of "len" when applied on
tuples or on lists. I mean:
$ len( ( 'foo' ) )
3
This is actually the length of a bracketed string, not a tuple.
Tuple's are defined by the existence of a comma...try:
>>len(('foo', ))
1
Nov 3 '08 #2
TP <Tr**********@P aralleles.inval idwrites:
Hi everybody,

I have a question about the difference of behavior of "len" when
applied on tuples or on lists. I mean:

$ len( ( 'foo', 'bar' ) )
2
$ len( ( 'foo' ) )
3
$ len( [ 'foo', 'bar' ] )
2
$ len( [ 'foo' ] )
1
For making a literal tuple, parentheses are irrelevant; only the
commas matter:
>>type( ('foo', 'bar') )
<type 'tuple'>
>>type( ('foo',) )
<type 'tuple'>
>>type( ('foo') )
<type 'str'>

However, for making a literal list, the brackets do matter:
>>type( ['foo', 'bar'] )
<type 'list'>
>>type( ['foo',] )
<type 'list'>
>>type( ['foo'] )
<type 'list'>

--
\ “The way to build large Python applications is to componentize |
`\ and loosely-couple the hell out of everything.” —Aahz |
_o__) |
Ben Finney
Nov 3 '08 #3
For making a literal tuple, parentheses are irrelevant; only the
commas matter:
I don't think I'd go so far as to say that the parentheses around
tuples are *irrelevant*... maybe just relevant in select contexts
>>def foo(*args):
... for i, arg in enumerate(args) :
... print i, arg
...
>>foo(1,2)
0 1
1 2
>>foo((1,2)) # these parens are pretty important :)
0 (1, 2)

pedantically-grinning-ducktyping-and-running-ly yers,

-tkc


Nov 3 '08 #4
TP:
This is actually the length of a bracketed string, not a tuple.
Tuple's are defined by the existence of a comma...try:
>len(('foo',) )
1
Time ago I have suggested to change the tuple literal, to avoid the
warts of the singleton and empty tuple, that may lead to bugs. But
using ASCII alone it's not easy to find something suitable and nice.

One of the suggestions of mine was to use (|...|) or [| x, ... |] to
denote tuples. This may lead to problems with the bitwise operators,
so the following two tuples:
t1 = ()
t2 = (x | y,)

Become (Fortress language uses similar liters, I think):
t1 = (||)
t2 = (| x OR y |)

Or this:
t1 = [||]
t2 = [| x OR y |]

Where OR, AND, XOR, NOT, SHL, SHR are the bitwise operators.
Having to type (| |) often is less handy, for example this code:

def divmod(a, b):
return a // b, a % b
d, r = divmod(10, 7)

becomes:

def divmod(a, b):
return (| a // b, a % b |)
(|d, r|) = divmod(10, 7)

Bye,
bearophile
Nov 3 '08 #5
be************@ lycos.com wrote:
[...]
Where OR, AND, XOR, NOT, SHL, SHR are the bitwise operators.
Having to type (| |) often is less handy, for example this code:
Which is precisely why bare parentheses are used. And remember, you
often don't need to put the parentheses in. While this kind of beginner
mistake is common it isn't one that's frequently repeated once the
learner understands the syntax.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Nov 3 '08 #6
Steve Holden:
While this kind of beginner
mistake is common it isn't one that's frequently repeated once the
learner understands the syntax.
You may be right, but I don't have to like it.
When you teach programming to people that have never done it before,
and you use Python, they spot similar inconsistences in the blink of
an eye and often look annoyed. They want a clean language, so you have
to explain them the difference between a practical engineering system
(like Python/Scheme or on the opposite C++) and an abstract system
that you can use to reason (like some parts of mathematics they know).
The good thing is that Python3 fixes some of those things :-)

Bye,
bearophile
Nov 3 '08 #7
Tim Chase wrote:
>For making a literal tuple, parentheses are irrelevant; only the
commas matter:

I don't think I'd go so far as to say that the parentheses around tuples
are *irrelevant*... maybe just relevant in select contexts
>>def foo(*args):
... for i, arg in enumerate(args) :
... print i, arg
...
>>foo(1,2)
0 1
1 2
>>foo((1,2)) # these parens are pretty important :)
0 (1, 2)

pedantically-grinning-ducktyping-and-running-ly yers,
I'll see your pedantry and raise you one:
>>foo()
foo(())
0 ()
--Scott David Daniels
Sc***********@A cm.Org

Nov 3 '08 #8
be************@ lycos.com writes:
Steve Holden:
>While this kind of beginner
mistake is common it isn't one that's frequently repeated once the
learner understands the syntax.

You may be right, but I don't have to like it.
When you teach programming to people that have never done it before,
and you use Python, they spot similar inconsistences in the blink of
an eye and often look annoyed. [...]
You can teach them that the comma is a terminator rather than a
separator (no more inconsistencies ), but that the python parser is
forgiving and understands when the last comma is missing if the
expression is not already meaningful.

I.e. one should write

(1, 2, 3,)

But python, being nice, understands when you write

(1, 2, 3)

Now consider this:

3 * (1 + 2)

What interpretations should python take of the brackets?
The good thing is that Python3 fixes some of those things :-)
And introduces some new inconsistencies for newcomers, e.g.

s = {1, 2, 3} # A set with 3 elements
s = {1} # A set with one element
s = {} # Surely, this should be an empty set!!

--
Arnaud

--
Arnaud
Nov 3 '08 #9
Arnaud Delobelle:
>And introduces some new inconsistencies for newcomers, e.g.
s = {1, 2, 3} # A set with 3 elements
s = {1} # A set with one element
s = {} # Surely, this should be an empty set!!
Are you able to list other inconsistencies ?

Python3 introduces one or two warts, but removes many more
inconsistencies , so for me it's a net gain.

So far for me, beside the one you have shown, there's only another
detail I don't like of Python3 (the removal of tuple unpaking in
function calls).

Bye,
bearophile
Nov 3 '08 #10

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

Similar topics

50
3658
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,
1
2145
by: richard | last post by:
bonjour je me connecte une base de donnes interbase/firebird en utilisant, KinterbasDB http://kinterbasdb.sourceforge.net/ pour ceux que ca interesse mais je pense que le probleme est le meme quel que soit la bdd j'aimerais acceder a un champs par sont nom plutot que par son index dans le record en cours, comme je fais maintenent
15
4028
by: Steve M | last post by:
Hello, I'm trying to figure out the index position of a tuple member. I know the member name, but I need to know the members index position. I know that if I use the statement print tuple that it will print the contents of that location. What I don't understand is if I know that foo is a member of tuple, how do I get foo's index position....
37
2364
by: Gregor Horvath | last post by:
Hi, >>>type() <type 'list'> >>>type(('1')) <type 'str'> I wonder why ('1') is no tuple????
8
5918
by: Captain Dondo | last post by:
I have an array(?) (sorry, I'm new* to python so I'm probably mangling the terminology) that looks like this: I want to replace every instance of 'tooth.seiner.lan' with 'localhost'. There may be lots and lots of these entries (they're pulled from my mythtv database). I could brute-force this by rewriting the whole thing and replacing
77
4373
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.
1
2866
by: Giovanni Toffoli | last post by:
Hi, I'm not in the mailing list. By Googling, I stepped into this an old post: (Thu Feb 14 20:40:08 CET 2002) of Jeff Shannon: http://mail.python.org/pipermail/python-list/2002-February/128438.html <<< def SortOnItem(mylist, index): templist = , line) for line in mylist ]
4
2245
by: laxmikiran.bachu | last post by:
Can we have change a unicode string Type object to a Tuple type object.. If so how ????
9
3476
by: bullockbefriending bard | last post by:
i have a large collection of python objects, each of which contains an integer 6-tuple as part of its data payload. what i need to be able to do is select only those objects which meet a simple tuple element wildcard matching criterion. e.g. given the following python objects: object A includes tuple (1,2,3,4,5,6) object B includes tuple...
0
7583
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...
0
7885
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. ...
1
7638
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...
0
7948
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...
0
5213
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...
0
3642
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...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2082
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
923
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...

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.