-1

in the line of code below, I'm trying to process track_ids, a set which does not allow indexing.

track_name = sp.track(track_ids[i])['name']

how do I convert track_ids into a list so I'm able to index it?

EDIT: this is the complete function:

def filterBelowThreshold(product, filter_name, track_ids, values, 
    xsongs, threshold):
    print product.upper(), 'PLAYLIST:'
    for i, x in enumerate(values):
        if x < threshold:
            track_name = sp.track(track_ids[i])['name']
            #append minding foreign track names
            xsongs.add(track_name.encode("utf-8"))
            print product.upper(),'-', "{} = {}".format(track_name.encode("utf-8"), x), filter_name
8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198
  • 2
    You can just go over it with a for loop can't you? And also, you could trying passing the set to `list()`. – Carcigenicate Oct 18 '16 at 15:28
  • 1
    Being it an not-indexable (without ordering) set, you have no way to guarantee that your index `i` in `values` actually refers to a specific `track_id` – fstab Oct 18 '16 at 15:33
  • What follows is the question, in what way the track_ids and the values are related and if so, wether you would preferably join them before calling the function to assure your order gets not messed up. (Or if you would want to apply a filter on the list) – Kim Oct 18 '16 at 15:35

3 Answers3

6

you can convert a set into a list by calling the function list(track_ids).

Please notice that the elements in this new list will not have a meaningful ordering, so accessing it like you are doing with an i index that enumerates over another list is not correct, assuming that you think that the elements in values and track_ids are somewhat related.

But, if you really want to get values and track_ids paired (likely being random pairings) you might try this more concise way:

for val, track_id in zip(values,list(track_ids)):
fstab
  • 4,801
  • 8
  • 34
  • 66
  • order is not a necessity here, as long as I end up with a list of `songs`(track_names) an another list with their corresponding `track_ids` – 8-Bit Borges Oct 18 '16 at 17:58
  • list to set does not preserve ordering. Is that true for set to list as well? – Allohvk Jun 29 '21 at 14:23
0

I would say like that:

[x for x in track_ids][index]
Louis Durand
  • 187
  • 9
0

No need to go for loop, just wrap your set with list function call, see an example below

#Index Doesn't work with set
>>> set([1,2,3])[1]
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: 'set' object does not support indexing

#convert set to list like this and indexing would work.
>>> list(set([1,2,3]))[1]
=> 2
saurabh baid
  • 1,819
  • 1
  • 14
  • 26