Alex Gordon
Alex Gordon

Reputation: 60811

python: appends only '0'

  big_set=[]
  for i in results_histogram_total:
    big_set.append(100*(i/sum_total))

big_set returns [0,0,0,0,0,0,0,0........,0]

this wrong because i checked i and it is >0

what am i doing wrong?

Upvotes: 0

Views: 105

Answers (4)

dan04
dan04

Reputation: 91189

In Python 2.x, use from __future__ import division to get sane division behavior.

Upvotes: 5

John La Rooy
John La Rooy

Reputation: 304355

try this list comprehension instead

big_set = [100*i/sum_total for i in results_histogram_total]

note that / truncates in Python2, so you may wish to use

big_set = [100.0*i/sum_total for i in results_histogram_total]

Upvotes: 3

Mark_Masoul
Mark_Masoul

Reputation: 1573

Probably has to do with float division.

i is probably less than sum_total which in integer division returns 0.

100 * 0 is 0.

Try casting it to a float.

Upvotes: 2

Andre Holzner
Andre Holzner

Reputation: 18695

If sum_total is an integer (what is sum_total.__class__ equal to ?), python seems to use integer division.

Try i / float(sum_total) instead.

Upvotes: 2

Related Questions