Home > Blockchain >  how to put value of for loop in list?
how to put value of for loop in list?

Time:09-08

i have a problem with my python code, i try to do a list from datas from a list, my code is here:

for i in arr_of_user_id:
    individual_user_id = i
    print(len(arr_of_user_id) #return 4

    #some code here
    #amount = result of my previous code
    print(amount)

#return this in the console:

10
212
2
454
#this is not a list, in just result of for loop 

so my question is: how can i have a list like [10, 212, 2, 454] ? i try to do

    list = []
    for i in arr_of_user_id:
        list.append(amount)
print(list)
# return  [10,10,10,10], so 4 time the same value

so how to put value of the 'for loop' in 1 list ?

CodePudding user response:

First of all, you should never use the name "list" as a variable name, since it is the name of the build-in function for creating lists.

new_list = []
for i in arr_of_user_id:
    individual_user_id = i
    print(len(arr_of_user_id) #return 4

    #some code here
    #amount = result of my previous code
    new_list.append(amount)

CodePudding user response:

I guess you almost got it right, just the indentation looks wrong.Maybe you should also use another variable naming for your list as list is a class name. Find the following example below, were I created a random numpy array as arr_of_user_id Hope this helps:

import numpy as np
arr_of_user_id = np.random.randint(1, 100, 5)

result = []

for i in arr_of_user_id:
    result.append(i)
print(result)

CodePudding user response:

i don't really understand your question, so there's multiple answers. In your code, you are trying to copy() your list in another.

You can do it this way :

my_lst = [10, 20, 30, 40, 50]
new_lst = []
for elem in my_lst:
    new_lst.append(elem)
print(new_lst)

But it's litteraly:

new_lst_from_copy = my_lst.copy()
print(new_lst_from_copy)

The value of the variable "amount" never changes in your loop, so you will always have the same value.

Don't use the word "list" as variable name :

list(something)

Hope this can help

  • Related