hakuna121
hakuna121

Reputation: 243

Stuck when trying to manually implement the pop method for lists

What I intended to do:

Implement a function called my_pop(), which is similar to the list pop() method. Take a list as input, remove the last object from the list and return it.

What I came up with:

# take an input of list;
# if not last item(determined by comparing index number): loop through the list and copy every item to new list
# if last item: pass

def my_pop(l):
    new = []
    l = list(l)
    for i in l:
        if l.index(i) == -1:
            pass
        else:
            new.append(i)
    return new

Problem: when run, it returns the list new as an exact copy of the old list l, failing to remove the last item of l; I haven't been able to figure out why my way don't work. General pointers greatly appreciated! Thank you.

Solution: thanks to the excellent answers below, I got to see why if l.index(i) == -1 won't work; Pasted here is a similar solution based on @jh314 's insight, but using a while loop instead:

# take an input of list;
# compare the index using c to determine if it's the last element in the list;

def pop(l):
    n = []
    l = list(l)
    c = 0
    while c < int(len(l)-1):
        n.append(l[c])
        c = c + 1
    else:
        pass

    return n

Upvotes: 2

Views: 2507

Answers (3)

Viktor
Viktor

Reputation: 279

    def my_pop(lst):
        if len(lst) <= 1 : # "if last item: pass"
            return
        last_item_in_list = lst[-1] # that is what we want to return 
        del lst[-1] 
        # deletes an an item from a list 
        # (see http://docs.python.org/2/tutorial/datastructures.html#the-del-statement )
        #
        return last_item_in_list

Upvotes: 0

jh314
jh314

Reputation: 27802

Your problem is that the last element's index (the result of l.index(i) where i is the last element of your list), does not equal -1.

This is a potential fix:

def my_pop(l):
    new = []
    l = list(l)
    for i in l:
        if l[-1] == i:
            pass
        else:
            new.append(i)
    return new

Or even better:

def my_pop(l):
    return l[:-1]

Upvotes: 2

Caleb
Caleb

Reputation: 191

There are a few problems with your code:

  1. The pop function returns not the new list, but the last element of the old list - it looks like your function is returning the new list.
  2. The index function always returns a positive index - remember that why you can access the last element of a list as -1, its real index is len(l)-1. Further, what happens if the last element is identical to another element in the list?

    [1,2,3,1].index(1)

    What do you think this expression evaluates to? Oops!

  3. I spoke of a "old" list and a "new" list, but they're really both the same list! Your code returns a modified copy of the list, but the old list remains the same. You can fix that by using a something like del, which modifies the list in-place.

Upvotes: 1

Related Questions