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?
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?
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 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])
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])
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.