Jatziri
Jatziri

Reputation: 33

'list' object cannot be interpreted as an integer - Is there a way to convert a list to integers?

I am new to the Python language. In one subject, they ask us to do the homework with this language and to investigate it on our own. In this part of the code, I first declare the range with the range(0, 1024) method, and the random numbers are generated with the sample method, and I believe that these are saved in a list, so what I want to do next is that these Numbers that were generated randomly convert them to binary, but I get this error:

TypeError: 'list' object cannot be interpreted as an integer

So I don't know if there is a way to convert a list to whole numbers or I don't know what else they would recommend me to do ...

This is my code:

y = list(range(0, 1024))
numRandom = sample(y, 10)
print(numRandom)
print(bin(numRandom))

Upvotes: 3

Views: 2641

Answers (3)

Unmitigated
Unmitigated

Reputation: 89224

You can use a List Comprehensions to create a new list with the binary representations of each number in the original list.

print([bin(x) for x in numRandom])

Upvotes: 2

TheLazyScripter
TheLazyScripter

Reputation: 2665

Using Map

print([*map(bin, random.sample(y, 10))])

Or Using List Comprehension

print([bin(x) for x in random.sample(y, 10)])

Upvotes: 1

Samwise
Samwise

Reputation: 71454

As the error says, numRandom is a list, not an integer. Specifically, it's a list of ten random ints.

To apply the bin function to the first element of the list, you could do:

print(bin(numRandom[0]))

You could iterate over the list and do this to each one with a for loop:

for num in numRandom:
    print(bin(num))

Or you could build a list of binary representations with a list comprehension:

print([bin(num) for num in numRandom])

Upvotes: 1

Related Questions