473,625 Members | 3,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sum and strings

I was browsing the Voidspace blog item on "Flattening Lists", and
followed up on the use of sum to do the flattening.
A solution was:
>>nestedList = [[1, 2], [3, 4], [5, 6]]
sum(nestedLis t,[])
[1, 2, 3, 4, 5, 6]

I would not have thought of using sum in this way. When I did help(sum)
the docstring was very number-centric: It went further, and precluded
its use on strings:
>>help(sum)
Help on built-in function sum in module __builtin__:

sum(...)
sum(sequence, start=0) -value

Returns the sum of a sequence of numbers (NOT strings) plus the
value
of parameter 'start'. When the sequence is empty, returns start.

The string preclusion would not help with duck-typing (in general), so
I decided to consult the ref doc on sum:

sum( sequence[, start])

Sums start and the items of a sequence, from left to right, and returns
the total. start defaults to 0. The sequence's items are normally
numbers, and are not allowed to be strings. The fast, correct way to
concatenate sequence of strings is by calling ''.join(sequenc e). Note
that sum(range(n), m) is equivalent to reduce(operator .add, range(n),
m) New in version 2.3.
The above was a lot better description of sum for me, and with an
inquisitive mind, I like to think that I might have come up with using
sum to flatten nestedList :-)
But there was still that warning about using strings.

I therefore tried sum versus their reduce "equivalent " for strings:
>>import operator
reduce(operat or.add, "ABCD".spli t(), '')
'ABCD'
>>sum("ABCD".sp lit(), '')
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: sum() can't sum strings [use ''.join(seq) instead]
>>>
Well, after all the above, there is a question:

Why not make sum work for strings too?

It would remove what seems like an arbitrary restriction and aid
duck-typing. If the answer is that the sum optimisations don't work for
the string datatype, then wouldn't it be better to put a trap in the
sum code diverting strings to the reduce equivalent?

Just a thought,

- Paddy.

Aug 18 '06 #1
52 3941
Sybren Stuvel wrote:
> Why not make sum work for strings too?

Because of "there should only be one way to do it, and that way should
be obvious".
I would have thought that "performanc e" and "proper use of English" was
more relevant, though.

</F>

Aug 18 '06 #2
Sybren Stuvel <sy*******@YOUR thirdtower.com. imaginationwrit es:
Because of "there should only be one way to do it, and that way should
be obvious". There are already the str.join and unicode.join methods,
Those are obvious???
Aug 18 '06 #3
Paul Rubin wrote:
Sybren Stuvel <sy*******@YOUR thirdtower.com. imaginationwrit es:
>Because of "there should only be one way to do it, and that way should
be obvious". There are already the str.join and unicode.join methods,

Those are obvious???
Why would you try to sum up strings? Besides, the ''.join idiom is quite
common in Python.

In this special case, ''.join is much faster than sum() which is why
sum() denies to concat strings.

Georg
Aug 18 '06 #4
Paul Rubin:
Sybren Stuvel:
Because of "there should only be one way to do it, and that way should
be obvious". There are already the str.join and unicode.join methods,

Those are obvious???
They aren't fully obvious (because they are methods of the separator
string), but after reading some documentation about string methods, and
after some tests done on the Python shell, you too can probably use
then without much problems.

Bye,
bearophile

Aug 18 '06 #5
be************@ lycos.com wrote:
Paul Rubin:
>>Sybren Stuvel:
>>>Because of "there should only be one way to do it, and that way should
be obvious". There are already the str.join and unicode.join methods,

Those are obvious???


They aren't fully obvious (because they are methods of the separator
string), but after reading some documentation about string methods, and
after some tests done on the Python shell, you too can probably use
then without much problems.
Using a bound method can make it a little more obvious.
>>cat = "".join
cat(['one', 'two', 'three'])
'onetwothree'
>>cat([u'one', u'two', u'three'])
u'onetwothree'
>>>
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Aug 18 '06 #6
Sybren Stuvel wrote:
Paddy enlightened us with:
Well, after all the above, there is a question:

Why not make sum work for strings too?

Because of "there should only be one way to do it, and that way should
be obvious". There are already the str.join and unicode.join methods,
which are more powerful than sum.

Sybren
I get where you are coming from, but in this case we have a function,
sum, that is not as geeral as it could be. sum is already here, and
works for some types but not for strings which seems an arbitrary
limitation that impede duck typing.

- Pad.

P.S. I can see why, and am used to the ''.join method. A newbie
introduced to sum for integers might naturally try and concatenate
strings using sum too.

Aug 18 '06 #7

Sybren Stuvel wrote:
Paddy enlightened us with:
Well, after all the above, there is a question:

Why not make sum work for strings too?

Because of "there should only be one way to do it, and that way should
be obvious". There are already the str.join and unicode.join methods,
which are more powerful than sum.

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Here is where I see the break in the 'flow':
>>1+2+3
6
>>sum([1,2,3], 0)
6
>>[1] + [2] +[3]
[1, 2, 3]
>>sum([[1],[2],[3]], [])
[1, 2, 3]
>>'1' + '2' + '3'
'123'
>>sum(['1','2','3'], '')
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: sum() can't sum strings [use ''.join(seq) instead]
>>>
- Pad.

Aug 18 '06 #8
Paddy wrote:
Sybren Stuvel wrote:
>Paddy enlightened us with:
Well, after all the above, there is a question:

Why not make sum work for strings too?

Because of "there should only be one way to do it, and that way should
be obvious". There are already the str.join and unicode.join methods,
which are more powerful than sum.

Sybren
I get where you are coming from, but in this case we have a function,
sum, that is not as geeral as it could be. sum is already here, and
works for some types but not for strings which seems an arbitrary
limitation that impede duck typing.
Only that it isn't arbitrary.
- Pad.

P.S. I can see why, and am used to the ''.join method. A newbie
introduced to sum for integers might naturally try and concatenate
strings using sum too.
Yes, and he's immediately told what to do instead.

Georg
Aug 18 '06 #9
Paddy wrote:
Here is where I see the break in the 'flow':
>>>1+2+3
6
>>>sum([1,2,3], 0)
6
>>>[1] + [2] +[3]
[1, 2, 3]
>>>sum([[1],[2],[3]], [])
[1, 2, 3]
>>>'1' + '2' + '3'
'123'
>>>sum(['1','2','3'], '')
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: sum() can't sum strings [use ''.join(seq) instead]
do you often write programs that "sums" various kinds of data types, and
for which performance issues are irrelevant?

or are you just stuck in a "I have this idea" loop?

</F>

Aug 18 '06 #10

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

Similar topics

20
5763
by: Ravi | last post by:
Hi, I have about 200GB of data that I need to go through and extract the common first part of a line. Something like this. >>>a = "abcdefghijklmnopqrstuvwxyz" >>>b = "abcdefghijklmnopBHLHT" >>>c = extract(a,b) >>>print c "abcdefghijklmnop"
17
7391
by: Gordon Airport | last post by:
Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently interchangeable in all circumstances (as long as they're paired) so there's no overloading to muddy the language. Of course there could be some interesting problems with current code that doesn't make a distinction, but it would be dead easy to fix...
16
2416
by: Paul Prescod | last post by:
I skimmed the tutorial and something alarmed me. "Strings are a powerful data type in Prothon. Unlike many languages, they can be of unlimited size (constrained only by memory size) and can hold any arbitrary data, even binary data such as photos and movies.They are of course also good for their traditional role of storing and manipulating text." This view of strings is about a decade out of date with modern programmimg practice. From...
4
10529
by: agent349 | last post by:
First off, I know arrays can't be compared directly (ie: if (arrary1 == array2)). However, I've been trying to compare two arrays using pointers with no success. Basically, I want to take three sets of character strings from the user. Then I want to run through each element and compare the two strings. If they match I print they match... I'm having a bit of trouble with the actual loop through each array using the pointers and comparing...
25
3541
by: Rainmaker | last post by:
Hi, Can anyone tell me an efficient algorithm to sort an array of strings? Keep in mind that this array is HUGE and so the algorithm should me efficient enough to deal with it. Thanks
6
1741
by: Broeisi | last post by:
Hello, I wrote the tiny progam below just to understand arrays and strings better. I have 2 questions about arrays and strings in C. 1. Why is it that when you want to assign a string to an character array that you must use the strcpy() function?
2
22594
by: Potiuper | last post by:
Question: Is it possible to use a char pointer array ( char *<name> ) to read an array of strings from a file in C? Given: code is written in ANSI C; I know the exact nature of the strings to be read (the file will be written by only this program); file can be either in text or binary (preferably binary as the files may be read repeatedly); the amount and size of strings in the array won't be known until run time (in the example I have it in...
19
3096
by: pkirk25 | last post by:
I wonder if anyone has time to write a small example program based on this data or to critique my own effort? A file called Realm List.html contains the following data: Bladefist-Horde Nordrassil-Horde Draenor-Alliance Nordrassil-Alliance Nordrassil-Neutral Draenor-Horde
95
5036
by: hstagni | last post by:
Where can I find a library to created text-based windows applications? Im looking for a library that can make windows and buttons inside console.. Many old apps were make like this, i guess ____________________________________ | | | ------------------ | | | BUTTON | | | ...
0
8696
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
8358
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
8502
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
7188
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...
1
6119
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4090
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
4195
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2621
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
2
1504
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.