Chamambom
Chamambom

Reputation: 127

Make a python for loop return a List of intergers

I have a python for loop like this

for i in view_overall_isp_ratings:
        #the int and the round is just for casting the values returned
        me = (int(round(i.avg_of_ratings)))
        print(me)

and this prints intergers like this 1
                                    1
                                    1
                                    1
                                    4

What i want

for it to produce a list like this 
    [ 1 ,1 ,1 ,1 ,4]

tried playing around with the [] but the least i could get was

 [1]
 [1]
 [1]
 [1]
 [4]

Can anyone assist

Upvotes: 1

Views: 286

Answers (1)

Mureinik
Mureinik

Reputation: 311978

You need to create a list (outside the loop!) and append to it in each loop iteration:

lst = []
for i in view_overall_isp_ratings:
    #the int and the round is just for casting the values returned
    lst.append(int(round(i.avg_of_ratings)))

print(lst)

Or, in a much cleaner fashion, you could use a list comprehension:

print([int(round(i.avg_of_ratings)) for i in view_overall_isp_ratings])

Upvotes: 1

Related Questions