George luke
George luke

Reputation: 27

Sorting out unique elements from a list to a set

I was writing a function to save unique values returned by a list "list_accepted_car" to a set "unique_accepted_ant". list_car_id is list with the value ['12','18','3','7']. When i run the code i am getting error , "unhashable list ". Can anyone suggest me what is the error?

list_accepted_car = []        #set to store the value list_accepted_car
unique_accepted_car = set()     #set to store the value unique_accepted_car
num_accepted = 2               #predifined value for the number of cars allowed to enter
def DoIOpenTheDoor(list_car_id):  #list_ant_id is a list of cars allowed to enter
    if len(list_accepted_car) < num_accepted:
        if len(list_car_id) > 0:
            list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])            
    unique_accepted_list = set(list_accepted_car)
    print unique_accepted_list
    return list_accepted_car

Upvotes: 0

Views: 75

Answers (3)

Błotosmętek
Błotosmętek

Reputation: 12927

Lists are not hashable objects, and only hashable objects can be members of sets. So, you can't have a set of lists. This instruction: list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])

appends a slice of list_car_id to list_accepted_car, and a slice of a list is a list. So in effect list_accepted_car becomes a list of lists, and that's why converting it to a set:

unique_accepted_list = set(list_accepted_car)

fails. Maybe what you wanted is extend rather than append? I can't say, because I don't know what you wanted to achieve.

Upvotes: 0

Nuageux
Nuageux

Reputation: 1686

Under the assumption that list_car_id looks like: [1,2,3,4,5]. You add in list_accepted_car a sublist of list_car_id, so list_accepted_car will look like [[1,2]] i.e. a list of a list. Then you should change

unique_accepted_list = set(list_accepted_car)

to

unique_accepted_list = set([x for y in list_accepted_car for x in y])

which will extract each element of the sublist and provide a flatten list. (There exists other options to flatten a list of list)

Upvotes: 1

Reut Sharabani
Reut Sharabani

Reputation: 31339

You are saving a list of lists, which can't be converted to a set. You have to flatten it first. There are many examples of how to do it (I'll supply one using itertools.chain which I prefer to python's nested comprehension).

Also, as a side note, I'd make this line more readable by separating to several lines:

list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])

You can do:

from itertools import chain
# code ...
unique_accepted_list = set(chain.from_iterable(list_accepted_car))

The best option would be to not use a list at all here, and use a set from the start.

Upvotes: 0

Related Questions