Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]
like image 885
P Moran Avatar asked Nov 06 '12 04:11

P Moran


People also ask

How do you remove the nth element from a list in Python?

Use list slicing to remove every Nth element from a list, e.g. del my_list[::2] . The value between the square brackets is the step which can be used to remove every Nth element from the list. Copied!

How do I remove a specific item from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.


2 Answers

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.

like image 85
Dietrich Epp Avatar answered Oct 12 '22 03:10

Dietrich Epp


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

for example

for sublist in list:
    del sublist[index]
like image 42
Myjab Avatar answered Oct 12 '22 04:10

Myjab