-1
for i in range(len(results_histogram)):
    if i!=len(results_histogram)-1:
      url+=str(results_histogram[i])+','

my if statement is checking whether i am on the last loop, but it is not working. what am i doing wrong?

Tim McNamara
  • 18,019
  • 4
  • 52
  • 83
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
  • Is this the complete statement? Don't be offended but are you actually reading documentation too? It is important that you learn to find answers yourself. And maybe you should read the documentation *before* you use Python... – Felix Kling Aug 03 '10 at 23:00
  • @Felix, that's ridiculous. Besides people learning in different ways, and experimentation being generally a great way to learn, NOBODY reads ALL the documentation to Python, or anything else, before using it. Don't be arrogant. – Kenan Banks Aug 03 '10 at 23:13
  • thanks kenan, i really do a learn a lot from asking questions and im very grateful for everyone's input – Alex Gordon Aug 03 '10 at 23:17
  • @Triptych: My wording was poor. Of course one does not have to read *all* the documentation. But based on the OP's previous questions, it seems that he has not even read the some basic tutorials that explain e.g. lists. Most of the questions could be answered by having a look at the documentation. And of course such questions are still valid questions here, but the rate of which the OP asked new questions just made me think. – Felix Kling Aug 04 '10 at 00:10

5 Answers5

7

To avoid the question slightly, you seem to have rewritten str.join:

','.join(results_histogram)

If you get an error like TypeError: sequence item 0: expected string, int found, then you can convert the intermediate results to a string with

','.join(map(str, results_histogram))

str.join is undoubtedly more efficient than concatenating multiple strings in a loop, because in Python, strings are immutable, so every concatenation results in the creation of a new string, which then has to be garbage collected later.


Specifically, your example is "not working" because you skip the last element entirely, when you only want to skip adding the comma. This is clear and obvious with a small example:

>>> x = [1,2,3]
>>> for i in range(len(x)):
...   if i != len(x) - 1:
...     print str(x[i]) + ',',
... 
1, 2,

So you could rewrite your example as

for i in range(len(results_histogram)):
    url += str(results_histogram[i])
    if i!=len(results_histogram)-1:
      url += ','

But you should still stick with str.join.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • why cant i do it the way i am currently doing it>?? – Alex Gordon Aug 03 '10 at 22:59
  • 1
    @I__: Because it is unnecessarily complicated. – Felix Kling Aug 03 '10 at 23:01
  • @I__: You can do it the way you currently are, but you shouldn't. Don't re-implement code when there is more instantly readable and debugged code that already solves your problem. – Merlyn Morgan-Graham Aug 03 '10 at 23:09
  • question: why do you have to include MAP why cant you just do; ','.join(str(results_histogram)) – Alex Gordon Aug 03 '10 at 23:12
  • 2
    answer: because results_hisogram is a list. map performs a function on the elements of that list. – Tim McNamara Aug 03 '10 at 23:21
  • Your answer is obviously correct, but wouldn't it be easier for a newcomer to use `','.join(str(r) for r in results_histogram)` rather than `','.join(map(str, results_histogram))`? They do the same thing, but the first is easier to understand, more idiomatic now, and may be slightly more efficient by not constructing the intermediate list. – Muhammad Alkarouri Aug 03 '10 at 23:51
2

I agree with @Mark Rushakoff in that using join would be the best. I wanted to just comment on this but I do not have enough rep to do so =(

Anyways, also look into the built-in enumerate() function. The documentation can be found here.

A way you could've coded your solution using enumerate would be:

for i, res in enumerate(results_histogram):
    url+=res
    if i != len(results_histogram)-1:
       url+=','

Assuming url is declared somewhere previously. Again, using join for your situation would be better. This is just showing you enumerate for future situations where you might want to do something besides string concatenation.

user389875
  • 71
  • 4
  • Wouldn't that be `if i != len(results_histogram) - 1:`? – jpsimons Aug 03 '10 at 23:34
  • +1 for using `enumerate`. One of the most underrated functions in the Python standard library, IMHO. Most importantly, it works even if `len()` isn't available (e.g. if you're dealing with a generator function that computes a sequence lazily). – Daniel Pryden Aug 03 '10 at 23:43
1

Mark is certainly right for your example, but sometimes cases like this occur where there doesn't exist such an elegant alternative. Then you could do something like:

if len(results_histogram):
    url += str(results_histogram[0])
    for i in range(len(results_histogram))[1:]:
        url += ',' + str(results_histogram[i])
thieger
  • 146
  • 5
1

Using a variable to increment through a list is generally unnecessary. A slice will return everything except the last element.

This example follows your syntax:

for el in results_histogram[:-1]:
    url += str(el) + ','

Or you can complete the whole thing with a generator expression:

','.join(str(el) for el in results_histogram[:-1])
Tim McNamara
  • 18,019
  • 4
  • 52
  • 83
0
ouput = "("
for telem in text[:-1]:
    output += "%s, " % telem 
output += "%s)\n" % text[-1:]
Sérgio
  • 6,966
  • 1
  • 48
  • 53