Store a value in an array inside one for loop

Question:

I would like to store each value of price in an array, getting it from a dict. I am a fresh at python, I spent hours trying to figure this out…

for item in world_dict:
     if item[1] == 'House':
       price = float(item[2])
       print p

The output is like:
200.5
100.7
300.9
...
n+100

However, I want to store it on this format : [200.5, 100.7, 300.9, …, n+100]

Asked By: A. Ayres

||

Answers:

Define a list and append to it:

prices = []
for item in world_dict:
     if item[1] == 'House':
       price = float(item[2])
       prices.append(price)

print(prices)

or, you can write it in a shorter way by using list comprehension:

prices = [float(item[2]) for item in world_dict if item[1] == 'House']
print(prices)
Answered By: alecxe

This a simple example of how to store values into an array using for loop in python
Hope this will help freshers to gain something when they search the above question

list = [] #define the array 

#Fucntion gets called here
def gameConfiguration():
n= int(input("Enter Number of Players : "))
    for i in range(0, n): 
        ele = (input("Name : ")) 
        list.append(ele) # adding the element to the array
    
    print(list[0]) #so you can print the element 1 
    print(list[1]) #so you can print the element 2 so on and soforth

gameConfiguration() # starts the execution of the fuction
Answered By: Niroshan Ratnayake

In simplest way, to store the value of for loop in array.

from array import *

ar = []

for i in range (0, 5, 1) :

    x = 3.0*i+1
    
    ar.append(x)
    
print(ar)

Output like this;

[1.0, 4.0, 7.0, 10.0, 13.0]
Answered By: sd_Dhara.45
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.