0

I have two lists and I'm trying to create multiple copies of numbers based on how many times they occur.

numbers = [0, 1, 2]
amount = [1, 2, 3]

I tried:

total = []
n = 0
for i in range(len(numbers)):
    product = numbers[n] * amount[n]
    n += 1
    total.extend(product)

But I got the error:

TypeError: 'int' object is not iterable.

My expected output is:

total = [0, 1, 1, 2, 2, 2]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
catzen
  • 75
  • 8
  • 1
    Change ```total.extend(product)``` to ```total.append(product)``` That will fix your type error, but the code is flawed in the logic, so you won't get the expected result. – Rashid 'Lee' Ibrahim Aug 26 '20 at 16:06
  • 1
    Why are you maintaining `n` when you can just use `i` - the loop's variable? – Tomerikoo Aug 26 '20 at 16:12
  • @Rashid'Lee'Ibrahim your suggested fix will make the code have flawed logic... OP's code simply has two brackets missing to make it work as expected, I wouldn't say his logic is flawed – Tomerikoo Aug 26 '20 at 16:18

2 Answers2

3

Use zip

result = []
for i, j in zip(numbers, amount):
    result.extend([i] * j)

print(result)

[0, 1, 1, 2, 2, 2]
sushanth
  • 8,275
  • 3
  • 17
  • 28
2

Your error is within the line:

product = numbers[n] * amount[n]

it doesnt result in a list but an integer. Since you're multiplying two numbers.

What you actually want is

product = [numbers[n]] * amount[n]

Try it out here: https://repl.it/repls/WholeHuskyInterfaces

adjan
  • 13,371
  • 2
  • 31
  • 48