How to transform a list into set in Python?

0

I'm trying to intersect the player list with the computer list, but I'm getting an error that goes like this: "line 13, in print (set (player) .intersection (computer)) TypeError: 'int' object is not iterable ".

Would anyone know where I'm going wrong?

from random import sample

lista = []
for numero in range(1,4):
    jogador = int(input(f'{numero}º número: '))
    lista.insert(numero, jogador)
print(lista)

jogo = list(range(1, 21))
computador = sample(jogo, 3)
print(computador)

print(set(jogador).intersection(computador))
    
asked by anonymous 25.05.2018 / 02:52

2 answers

1

Notice what you did:

print(set(jogador).intersection(computador))

But jogador will be integer type because:

jogador = int(input(f'{numero}º número: '))

An integer is not iterable, so it can not be converted to a set by doing set(jogador) , just like the error message reported. Since you store the read values in jogador in the lista list, I believe the correct would be:

print(set(lista).intersection(computador))
    
25.05.2018 / 03:19
1

It is not always possible to convert the contents of a list to a set because of the different nature of each type, see:

lst = [ 1, 2, 3, 4, 1, 2, 3, 4 ]
s = set( lst )
print( s )

Output:

set([1, 2, 3, 4])

Note that set only supports single values, while list supports any set of values.

    
25.05.2018 / 18:11