I need help figuring how to work around removing a 'column' from a nested list to modify it.
Say I have
L = [[1,2,3,4],
[5,6,7,8],
[9,1,2,3]]
and I want to remove the second column (so values 2,6,1) to get:
L = [[1,3,4],
[5,7,8],
[9,2,3]]
I'm stuck with how to modify the list with just taking out a column. I've done something sort of like this before? Except we were printing it instead, and of course it wouldn't work in this case because I believe the break conflicts with the rest of the values I want in the list.
def L_break(L):
i = 0
while i < len(L):
k = 0
while k < len(L[i]):
print( L[i][k] , end = " ")
if k == 1:
break
k = k + 1
print()
i = i + 1
So, how would you go about modifying this nested list? Is my mind in the right place comparing it to the code I have posted or does this require something different?
Remove items from a Nested List. If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item. If you don't need the removed value, use the del statement.
Delete the column del is also an option, you can delete a column by del df['column name'] . The Python would map this operation to df.
Select the column header, and then select Column settings > Format this column. Select any column header, and then select Column settings > Show/hide columns. Select the column header you want to delete and select Column settings > Edit > Delete. Delete is at the bottom of the menu.
How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.
You can simply delete the appropriate element from each row using del
:
L = [[1,2,3,4], [5,6,7,8], [9,1,2,3]] for row in L: del row[1] # 0 for column 1, 1 for column 2, etc. print L # outputs [[1, 3, 4], [5, 7, 8], [9, 2, 3]]
If you want to extract that column for later use, while removing it from the original list, use a list comprehension with pop
:
>>> L = [[1,2,3,4],
... [5,6,7,8],
... [9,1,2,3]]
>>>
>>> [r.pop(1) for r in L]
[2, 6, 1]
>>> L
[[1, 3, 4], [5, 7, 8], [9, 2, 3]]
Otherwise, just loop over the list and delete the fields you no longer want, as in arshajii's answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With