darrenbarren
darrenbarren

Reputation: 21

for loop in python; creating a list that holds proportions

I'm currently stuck in a rut trying to create a for loop.

Here's my objective: I want to create a list holding the proportion of people in each age group for e.g.: the proportion of people in age group 5-10 would be 500/2000 = 0.25

population of people = 2000 Of which 3 age group exists: "5-10", "11-20", "21-30" No. of people in each age group respectively: 500, 700, 800

this is what I did:

n_pop = 2000
label_list = ['5-10', '11-20', '21-30']
sub_pop = [500, 700, 800]
proportion = []
for i in range(len(sub_pop)):
    proportion = sub_pop[i]/ n_pop
print(proportion)

Not sure where I went wrong with the code.

Upvotes: 0

Views: 911

Answers (3)

vash_the_stampede
vash_the_stampede

Reputation: 4606

This would be a good place to try out using a dictionary, How about something like this:

pop = 2000
age_groups = {'5-10': 500, '11-20': 700, '21-30': 800}
proportion = {}
for k, v in age_groups.items():
    percentage = v/2000
    proportion[k] = int(percentage * 100)

print(proportion, '\n')

for i in proportion:
    print(f"Age group {i} is {proportion[i]}% of Population {pop}")

I included two print methods to give you some ideas what you could do with this

(xenial)vash@localhost:~/python/stack_overflow$ python3.7 loop_pop.py 
{'5-10': 25, '11-20': 35, '21-30': 40} 

Age group 5-10 is 25% of Population 2000
Age group 11-20 is 35% of Population 2000
Age group 21-30 is 40% of Population 2000

Upvotes: 1

brno32
brno32

Reputation: 424

You should specify what your intended outcome is. Since you've declared proportion as an empty array, I assume you want to populate it.

You are overwriting the variable proportion with every iteration of your loop.

for i in range(len(sub_pop)):
    proportion = sub_pop[i]/ n_pop
    print(proportion)

The first iteration of the loop, e.g., when i is 0, proportion is equal to a float, the first proportion. Then, when it's 1, you overwrite it and it's then equal to the second proportion. The same goes for the third.

As Sruthi, suggested, you need to add to this list (as opposed to overwriting your empty list with a brand new value) with append. https://www.programiz.com/python-programming/methods/list/append

I'd also rename proportion to proportions if its use is intended to be for storing all of your proportions. Clear variable names can do a lot to help avoid confusion.

Upvotes: 1

Sruthi
Sruthi

Reputation: 3018

You're almost there!

Just append the values to the list proportion.append(sub_pop[i]/ n_pop) instead of assigning them to the list

for i in range(len(sub_pop)):
    proportion.append(sub_pop[i]/ n_pop)

Upvotes: 1

Related Questions