简体   繁体   中英

Multiple single lists within the same index

I am facing this problem after downloading data from a certain API, the data is downloaded in json format.

for i in range(color_id):
            testing1= [colors_full_list[i]['name']]
            print(testing1)

above is my code and it results in a list of strings.

(Ie: ['orange'] 
      ['apple'] 
      ['pear'] ) 

When I try to index it -> testing1[0], the above appears, but then I try to index it like testing1[1], there would be some error that it's out of range.

        `len(testing1)`

results in 1,1,1.

I want my end result to be

      `['orange' , 'apple', 'pear']`  

and have tried multiple solutions i could found on the web but still couldn't get it to work.

please help, thank you!

What you are doing is overriding the variable for every iteration of loop, so after completion of the for loop you are left with only one item in

testing1

What you want to do is to append the elements to a list which can easily achieved by declaring an empty list outside the for loop and then call append() function on the list for every element.

result = []
for i in range(color_id):
    result.append(colors_full_list[i]['name'])
print(result)

This will give you the desired result

['orange' , 'apple', 'pear']

You can try simply appending them to list. So, your code goes like:

array_required = []
for i in range(color_id):
     array_required.append(colors_full_list[i]['name'])

This will give you expected output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM