0

Say we have an array like a = [['a','b','c'], ['aber', 'jsfn', 'ff', 'fsf', '003'], [...] ...] where each element can be of different size. What I want to do is to delete the last item of each sub-array if it matches the condition I set. So I have:

for x in range(len(a)):
    if the last item in x matches some condition that is set:
        then remove the last item from x

Since I am dealing with an array, I tried a.remove(-1) but this is wrong. So, is there any simple way of doing this?

Just as an example, if I had:

for x in range(len(a)):
        if the last element of each sub-array starts with an "S":
            then remove the last item from that sub-array

How can I approach this? Any example or a link to some tutorial is much appreciated.

Trevor
  • 13,085
  • 13
  • 76
  • 99
Joojo Jobala
  • 13
  • 1
  • 3
  • possible duplicate of [Remove object from a list of objects in python](http://stackoverflow.com/questions/9754729/remove-object-from-a-list-of-objects-in-python) – Ben Glasser Feb 03 '15 at 17:44
  • This question may be a little more nuanced than the possible duplicate simply because it's referring to moving items from a sub-array. – Trevor Feb 03 '15 at 17:55

6 Answers6

1

Python lists support del which is by index:

>>> l = [1,2]
>>> del l[-1]
[1]

.remove(value) removes the first matching value.

.pop(value) is the same as remove but it returns the value that is removed, if you do not give it a value it will "pop" the last item off the list.

Ryan O'Donnell
  • 617
  • 6
  • 14
1

What you have here is a list of lists rather than an array as such. On this basis, you can do the following:

a = [['a','b','c'], ['aber', 'jsfn', 'ff', 'fsf', '003'], ['d', 'Starts With S']]  

for sublist in a:
    if sublist[-1].startswith("S"):
        sublist.pop()

print a

Which yields when run:

[['a', 'b', 'c'], ['aber', 'jsfn', 'ff', 'fsf', '003'], ['d']]
jlb83
  • 1,988
  • 1
  • 19
  • 30
  • Instead of the last element, could you pick any element in between? So instead of if sublist[-1].startswith("S"):, would if sublist[i].startswith("S"): be doable? – Joojo Jobala Feb 04 '15 at 06:50
  • @JoojoJobala - Absolutely, you could use any specific index instead of `-1` - though if your sublists are of variable length, then you would want to check the length first. Instead of using `pop()` with no arguments (which removes the last element), you would use `pop(i)` – jlb83 Feb 04 '15 at 08:43
0

You can pass the element you want to remove into remove(), or use pop() if you just want to remove the last element, see the following example:

>>> a = [['a','b','c'], ['aber', 'jsfn', 'ff', 'fsf', '003']]
>>> a[0].remove(a[0][1])  # a[0][1] is 'b'
>>> a[0]
['a', 'c']
>>> a
[['a', 'c'], ['aber', 'jsfn', 'ff', 'fsf', '003']]
>>> a[1].pop()  # remove the last element of a[1]
'003'
>>> a
[['a', 'c'], ['aber', 'jsfn', 'ff', 'fsf']]
Paul Lo
  • 6,032
  • 6
  • 31
  • 36
0

this has likely been answered here Remove object from a list of objects in python

but to reiterate, you can pop the specific index you want like this

for x in range(len(a)):
        if the last element of each element starts with an "S":
            array.pop(x)
Community
  • 1
  • 1
Ben Glasser
  • 3,216
  • 3
  • 24
  • 41
0

First off, if you only care about the last element in the array, then you don't need to iterate over the entire thing.

Just check if the final item in the array starts with "S", then use del a[-1] if it matches.

Similar question was asked here

Community
  • 1
  • 1
ifyadig
  • 51
  • 1
  • 10
0

First of all, never write this: for x in range(len(a)). It is working, but not appreciated in Python community.

Python can walk over array itself, use for element in lst. The latter construct however, doesn't allow to remove elements, but there are many ways to walk over list without for statement, i.e.:

There are several approaches to delete element too:

  • lst.remove(value) deletes all elements that are equal to value
  • filter(pred, lst) removes all elements that match to predicate pred and returns "filtered" list. I.e. lst = filter(lambda el: el[-1].startswith("S"), lst) removes all sublists if their last elements starts with "S".
  • lst.pop([i]) or lst[i] - remove and return element with index i. For pop index is optional - by default it is last element
  • Slice array so it wouldn't contain needed element. I.e. lst[:i] returns elements of list from 0 to i. So to delete last element you may just write lst = lst[:-1]

So your example may look like this:

if all(el[-1].startswith("S") for el in a):
      a.pop() 

Note that I didn't wrote braces around list comprehension - that is special form of it called generator comprehension.

You may however use for-else construct for same purposes:

for el in a:
    if not el[-1].startswith("S"):
        # Last element of sublist is not starts with "S", do nothing
        break
else:
    # We walked over entire list and never called break, so 
    # all elements matched. Delete the last element!
    a = a[:-1]

Take your pick.

myaut
  • 11,174
  • 2
  • 30
  • 62