Home > Enterprise >  Deleting elements of lists in an array
Deleting elements of lists in an array

Time:12-15

I have a long array, and each element is a list of 4 numbers. How do I delete the 4th number in each list in the array, so that the array becomes composed of lists of 3 elements?

I tried the pop and delete method, but it keeps deleting the 4th list in my array, not all of the 4th elements in my list.

CodePudding user response:

arr = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]

[ l[:-1] for l in arr ]

or if you want to mutate the array in place

for l in arr:
    l.pop()
arr

CodePudding user response:

  • This is a best guess since you did not post your code along with the issue.

It sounds like the problem is that you are not accessing the 2nd dimension of the array that you are trying to delete from.

Assuming your lists are of the form:

myList = [[1,2,3,4],['a','b','c','d'],[5,6,7,8],['w','x','y','z']]

In-order to delete the 4th element of each array, you'll need to index into both sets of arrays.

so to access the 4th element of the first array, you would need

myList[0][3]

Consider trying something along the lines of:

for i in range(0,4):
    myList[i] = myList[i][:-1]

That should change you original list to what you are looking for.

a simple running example in python would be

myList = [[1,2,3,4],['a','b','c','d'],[5,6,7,8],['w','x','y','z']]

for item in myList:
    print(item)

for i in range(4):
    myList[i] = myList[i][:-1]

for item in myList:
    print(item)
  • Related