How do I delete the Nth list item from a list of lists (column delete)?

29,600

Solution 1

You could loop.

for x in L:
    del x[2]

If you're dealing with a lot of data, you can use a library that support sophisticated slicing like that. However, a simple list of lists doesn't slice.

Solution 2

just iterate through that list and delete the index which you want to delete.

for example

for sublist in list:
    del sublist[index]

Solution 3

You can do it with a list comprehension:

>>> removed = [ l.pop(2) for l in L ]
>>> print L
[['a', 'b', 'd'], [1, 2, 4], ['w', 'x', 'z']]
>>> print removed
['d', 4, 'z']

It loops the list and pops every element in position 2.

You have got list of elements removed and the main list without these elements.

Solution 4

A slightly twisted version:

index = 2  # Delete column 2 
[(x[0:index] + x[index+1:]) for x in L]

Solution 5

[(x[0], x[1], x[3]) for x in L]

It works fine.

Share:
29,600
P Moran
Author by

P Moran

Engineer doing signal processing among everything else needed to run a consulting company. Using Yocto to build kernels for custom embedded devices. Using Qt4/5 for user interface design.

Updated on January 09, 2020

Comments

  • P Moran
    P Moran over 4 years

    How do I delete a "column" from a list of lists?
    Given:

    L = [
         ["a","b","C","d"],
         [ 1,  2,  3,  4 ],
         ["w","x","y","z"]
        ]
    

    I would like to delete "column" 2 to get:

    L = [
         ["a","b","d"],
         [ 1,  2,  4 ],
         ["w","x","z"]
        ]
    

    Is there a slice or del method that will do that? Something like:

    del L[:][2]
    
  • DSM
    DSM over 11 years
    Aside from the fact that using a listcomp for its side effects is generally disfavoured, this won't work unless the element you're removing happens to be first in the list. For example, if one of the sublists is [1,2,1,3], then the remove will return [2,1,3], not [1,2,3].
  • user3085931
    user3085931 about 8 years
    this solution is slow
  • Myjab
    Myjab about 8 years
    Could you please then let me know what is the best ever solution for this Prob :)
  • DJ_Stuffy_K
    DJ_Stuffy_K over 6 years
    how do I save the resulting newlist into a new variable?
  • Dietrich Epp
    Dietrich Epp over 6 years
    @DJ_Stuffy_K: This technique doesn't create new lists, it modifies the existing lists. However, you can copy the lists beforehand. new_L = [list(row) for row in L]... this is just one way to do things, it will create a shallow copy of each row, so when you modify new_L the original L will be unmodified.