tags:

views:

129

answers:

4
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?

+7  A: 

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
why cant i do it the way i am currently doing it>??
I__
@I__: Because it is unnecessarily complicated.
Felix Kling
i am not getting an error when i do the +
I__
wowoow!! this is pretty sweeeeeeeeeeet!
I__
@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
question: why do you have to include MAP why cant you just do; ','.join(str(results_histogram))
I__
answer: because results_hisogram is a list. map performs a function on the elements of that list.
Tim McNamara
thank you very much tim!
I__
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
+1  A: 

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
+1  A: 

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
+2  A: 

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.

Wouldn't that be `if i != len(results_histogram) - 1:`?
darkporter
Yes, fixed sorry bout that
+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