-2

I put my coding in IDLE and got error message

TypeError: can only concatenate list (not "int") to list.

Why the python doesn't accept index in values[index] as an int? What should I do with this problem?

def repeat_elem (values, index, num_times):
    # this function returns a new list in which the element of 'values' 
    # at position 'index' has been repeated 'num_times' times
    return values[:index] + values[index]*(num_times - 1) + values[index+1:]
DYZ
  • 55,249
  • 10
  • 64
  • 93
Mo Kim
  • 11
  • 1
  • 1
    `values[index]` is a number. If you multiply it by another number, it is still a number. You need `[values[index]]`, which is a list consisting of one number. – DYZ Sep 27 '18 at 03:18
  • what type do you think this: `values[index]*(num_times - 1)` is? – njzk2 Sep 27 '18 at 03:18
  • You could probably write it more elegantly using generators. – Paul Rooney Sep 27 '18 at 03:27
  • Why do you think `index` is the problem? – melpomene Sep 27 '18 at 03:30
  • If you haven't already, try adding some debugging (see if each value works, and mark the one giving you the problem) my guess would be that values[index]*(num_times - 1) is the problem, as your value at index*num_times -1 (which is an int) can't be added to values[:index]; were you trying to get: values[(index*num_times-1)]? Best of luck! – Steve Byrne Sep 27 '18 at 03:45
  • Thx guys.It perfectly work now – Mo Kim Sep 27 '18 at 18:16

1 Answers1

0

Try this:

def repeat_elem (values, index, num_times):
    # this function returns a new list in which the element of 'values'
    # at position 'index' has been repeated 'num_times' times
    return values[:index] + ([values[index]] * num_times) + values[index+1:]

In the code above:

  • repeat_elem([1, 2, 3], 0, 5) returns [1, 1, 1, 1, 1, 2, 3]
  • repeat_elem([1, 2, 3], 1, 5) returns [1, 2, 2, 2, 2, 2, 3]
  • repeat_elem([1, 2, 3], 2, 5) returns [1, 2, 3, 3, 3, 3, 3]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Joey deVilla
  • 8,403
  • 2
  • 29
  • 15