Python - Append items to a list while making https requests inside a loop
<p>I am making requests to <code>SPotify API</code> inside a <code>for loop</code>, like so:</p>

<pre><code>track_ids = []
#get track_ids
for track in random.sample(pitchfork_tracks, 10):
    results = sp.search(q=track, type='track') #here I call Spotify endpoint
    items = results['tracks']['items']
    for t in items:
        track_ids.append(t['uri'])
return track_ids
</code></pre>

<p>I can <code>print</code> every <code>t</code> alright, but if I try to <code>return</code> <code>track_ids</code>, console returns me nothing.</p>

<p>Log tells me:</p>

<pre><code>2016-10-03 23:55:49 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): accounts.spotify.com
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] DEBUG: "POST /api/token HTTP/1.1" 200 None
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] DEBUG: "GET /v1/search?q=Rushes&amp;limit=10&amp;type=track&amp;offset=0 HTTP/1.1" 200 None
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
2016-10-03 23:55:51 [requests.packages.urllib3.connectionpool] DEBUG: "GET /v1/search?q=Opposite+House&amp;limit=10&amp;type=track&amp;offset=0 HTTP/1.1" 200 None
2016-10-03 23:55:51 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
</code></pre>

<p>it looks like starting and ending connections over and over has something to do with it...or am I missing something obvious here?</p>

<p>how can I solve this and manage to build my <code>track_ids</code> <code>list</code>?</p>

<p><code>track_ids</code> scope is inside your function. To print list you can do like this </p>

<pre><code>track_ids = yourfunction()
print track_ids
</code></pre>

<p>OR </p>

<p>you can make <code>track_ids</code> list global and declare it outside of your function. </p>

python for-loop python-requests spotipy