0

I want every element in l(which is a list) to be added to a. When I run the function, it gives me '[]' every time. How can I fix this?

def sim(l):
    a = []
    if len(l)>0:
        a = a.append(l.pop())
        l.pop()
        return sim(l)
    return a
2
  • 3
    list.append() returns None. Commented Apr 6, 2014 at 4:23
  • @wwii, You should post that as an answer along with a suggested improvement or alternative. Commented Apr 6, 2014 at 4:25

4 Answers 4

2

Several things are wrong:

You shouldn't use lowercase L for a variable name - it looks like one

At the top of the function you assign an empty list to a - ultimately sim will be called with an empty list, then a will be assigned an empty list, the conditional statement will fail and sim will return an empty list.

Inside the conditional statement you assign the return value of list.append() to a. The return value is None so whatever a was before, it gets wiped out.

Inside the conditional statement you pop() two items out of your control list

An empty list has a boolean value of false so there is no need to explicitly check its length,

def sim(el, a = None):
    if el:
        a.append(el.pop())
        return sim(el, a)
    return a

I was taught to write the base case of a recursive function as the first statement:

def sim(el, a = None):
    if not el:
        return a
    a.append(el.pop())
    return sim(el, a)
Sign up to request clarification or add additional context in comments.

Comments

1

append() doesn't return anything but does update the existing list. In other words, by trying to assign the result of the append() method, you're setting a to nothing after you have already appended the item.

Comments

0

Your Code :def sim(l): a = []

when you call Function recursively return sim(l) every time it is call sim(l) and a=[] is empty.

Try This :

        def sim(l,a):
            if len(l)>0:
                 a.append(l.pop())
                 print a
                 return sim(l,a)
        return a

enter image description here

Comments

0

Is this a homework assignment where you're required to do it in a certain (overly complicated) way? Because if not, you can add one list to another in Python like so:

>>> l = [1, 2, 3]
>>> a = []
>>> a.extend(l)
>>> a
[1, 2, 3]

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.