yassoplaya
yassoplaya

Reputation: 67

How to fill a new list with elements of another list

I want to fill an empty list, I don't know how to exactly tell you want I want to to do, I think you can understand if I provide some code.

So I have this list, this is a list of integers basicaly.

sIDs = list(opl.keys())

I want to make a new list and fill it like this.

region = form.cleaned_data["region"]
for x in sIDs:

   sid = x
   url = "https://" + region + ".api.riotgames.com/lol/summoner/v4/summoners/" + sid + "?api_key=" + api_key
response = requests.get(url).json()
pid = response["profileIconId"]
newlist[i] = pid

How can I accomplish this ?

Upvotes: 0

Views: 1231

Answers (2)

artemis
artemis

Reputation: 7281

You would first need to write a line to create the newlist list, so something like: newlist = [] which would give you a blank list

Then, you would want to fill the new list with each item that you create in your original list, so you could edit your code to the following:

sid = list(opl.keys())
# Declaring a blank new list
newlist = []
region = form.cleaned_data["region"]
for x in sid:
# Fix an issue where you were constructing a url with the sid array and not the element x
    url = "https://" + region + ".api.riotgames.com/lol/summoner/v4/summoners/" + x + "?api_key=" + api_key
    # Move these inside so they are created for every item inside of the sid list
    response = requests.get(url).json()
    pid = response["profileIconId"]
    # add that pid to your new list
    newlist.append(pid)

There are comments within that explain.

Upvotes: 1

Philip H.
Philip H.

Reputation: 71

You should just be able to initialize your list with newlist = [] and then use newlist.append(pid).

If you know in advance how many elements you need to store in newlist, use newlist = [0] * n instead (with n being the number of elements to store). Then you can call your list with newlist[i] in a for-loop.

Upvotes: 1

Related Questions