1

I'm trying to write a program that generates a list of ten random integers from 1-5 inclusive, then prints the number each time each integer repeats. Then prints a second list with the duplicates removed. Right now I'm having an issue even getting the first list to generate at all. I keep getting TypeError: 'int' object is not iterable

This is what I have so far:

def randomTen():
    """return list of ten integers and the number of times each one
    appears"""
    firstList= []
    for num in range(1,11):
        x= int(random.randint(1,6))
        list1= firstList.append(x)
    print(list1)
6
  • 1
    You want append, not extend. Commented Mar 11, 2013 at 15:26
  • Thanks. I changed that, but now it just returns 'None' Commented Mar 11, 2013 at 15:28
  • 1
    Yes, this is how append() works. It changes the source list ("firstList") and doesn't return anything. Commented Mar 11, 2013 at 15:29
  • Additionally, your function will continue to return None until you return something with the return keyword. Commented Mar 11, 2013 at 15:30
  • 1
    That said, a list comprehension like firstList = [random.randint(1,6) for num in range(10)] is a more "pythonic" way to do the same. Commented Mar 11, 2013 at 15:31

3 Answers 3

4

First note that this could be done more easily with a list comprehension:

firstList = [random.randint(1,6) for num in range(1, 11)]

As for your function, you needed to do:

firstList= []
for num in range(1,11):
    x= int(random.randint(1,6))
    firstList.append(x)
print(firstList)

append doesn't return anything, it changes the list in place.

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't randint(1,6) be randint(1,5)? From the OP: "a list of ten random integers from 1-5 inclusive"
@Robᵩ: I was following the OP's lead, but you are certainly correct!
1
def randomTen():
    """return list of ten integers and the number of times each one
    appears"""
    firstList= []
    for num in range(1,11):
        x= int(random.randint(1,6))
        firstList.append(x)
    return firstList

You create an empty list firstList, append elements to it, and then return it.

Comments

0

1) x is an integer, not a list. So just use

list1 = firstList.append(x)

2) If you want to remove replicates, you may just want to convert the list to a set :

print(set(list1))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.