DIGIT-ARC read-only archive · snapshot: July 23, 2026

python code not running..

4 posts · originally from https://geek.digit.in/community/threads/python-code-not-running.155165/

ritvij
ritvij Original post #1
Apr 6, 2012 at 12:44 PM
here's the question:
define a procedure that takes in two inputs a list and a number(n) and outputs a new list that contains the original elements of list but repeated n times..

for ex:
if input list a is [1, 2, 3] and n=2
answer: [1,1, 2, 2, 3, 3]
or
if input list is [1, 0, 1] and n=0
answer: []

my code:
Code:
def explode_list(a, n):
      while(n!=0):
             for e in a:
                  a.append(e)
             n=n-1
      a=a.sort()
      return a

can anyone help as to where i went wrong..
nbaztec
nbaztec #2
Apr 6, 2012 at 2:50 PM
here's the question:
define a procedure that takes in two inputs a list and a number(n) and outputs a new list that contains the original elements of list but repeated n times..

for ex:
if input list a is [1, 2, 3] and n=2
answer: [1,1, 2, 2, 3, 3]
or
if input list is [1, 0, 1] and n=0
answer: []

my code:
Code:
def explode_list(a, n):
      while(n!=0):
             for e in a:
                  a.append(e)
             n=n-1
      a=a.sort()
      return a

can anyone help as to where i went wrong..

You are destroying/decrementing the value of n after each while iteration. Make the while loop as
Code:
   for i in range(0, n): 
          ...

A better approach is scanning each element and duplicating it in a new list.

Code:
   b = []
   for e in a
      for i in range(0, n): 
         b.append(e)
   return b
ritvij
ritvij #3
Apr 6, 2012 at 5:18 PM
thanks a lot.. BTW, what was wrong in degrading the value of n??
nbaztec
nbaztec #4
Apr 6, 2012 at 6:14 PM
thanks a lot.. BTW, what was wrong in degrading the value of n??

Since you need that value for each element e. The next element will have 0 value of n from your while loop.