How to turn a list into a set in Python?

Asked

Viewed 1,305 times

0

I’m trying to intersect the player list with the computer list, but I’m getting an error that says "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))
  • 1

    The two variables will be only an integer value and not a set, so there is no way to calculate the intersection between them. What exactly do you need to do? You do nothing with the variable lista?

  • As both will receive 3 values I thought this would be a set. I wanted to know the intersection of the 3 values given by the user with the 3 values that the computer will choose. I used the list to create the player variable list.

  • 1

    Are you sure it should be set(jogador) and not set(lista)?

  • Wow, that’s right, thank you so much.

2 answers

1

It is not always possible to convert the contents of a list for a set due to the different nature of each of these types, see only:

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

Exit:

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

Note that the set supports only unique values, equating to list supports any set of values.

1


Realize that you did:

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

But jogador will be the whole kind, because:

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

An integer is not eternal and therefore cannot be converted for a making set set(jogador), as the error message reported. Since you store the read values in jogador on the list lista, I believe the right thing would be:

print(set(lista).intersection(computador))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.