Reputation: 23
I would like to know if there's any way to remove an index in a list within a list. For example, given [[1,2,3],[4,5,6],[7,8,9]]
, I would like to remove the the first element of each list so that it becomes [[2,3],[5,6],[8,9]]
. I can do a for loop to slowly remove them but I was wondering if there's a more efficient manner to do so?
Upvotes: 1
Views: 1460
Reputation: 13120
For small list
s as in your example, doing something like list.pop(0)
is OK:
nested = [[1,2,3], [4,5,6], [7,8,9]]
for inner in nested:
inner.pop(0) # Remove first element of each inner list
However, as list
s are basically implemented as arrays (of pointers), removing the first element means that all other elements has to be shifted back by one, resulting in a lot of (pointer) copying if your list
s are large. Also, using inner[1:]
rather than inner.pop(0)
does not solve the problem, as inner[1:]
creates a new list
rather than returning a view.
One way out is to make the redundant elements appear as the last element instead of the first, so that you can do inner.pop()
instead, which removes the last element. No further shifting/copying is then required.
Another solution is to switch out your data structure from a list
to a deque
("double-ended queue"). This has a popleft()
method, which is equivalent to pop(0)
but fast, as deque
s support fast popping from both ends:
import collections
nested = [[1,2,3], [4,5,6], [7,8,9]]
nested = [collections.deque(inner) for inner in nested] # list of deques
for inner in nested:
inner.popleft() # Remove first element of each inner list, fast!
Upvotes: 0
Reputation: 121
I would say you have two options.
You can use pop()
:
for item in list:
item.pop(0)
Or recreate a new list :
list2 = [item[1:] for item in list]
Upvotes: 0
Reputation: 105
You can do it with iterating over the list, and then call the pop() function on the inner list. This will remove an element at the specified index.
test_list = [[1,2,3],[4,5,6],[7,8,9]]
for i in test_list:
i.pop(0)
print(test_list)
output: [[2, 3], [5, 6], [8, 9]]
Upvotes: 1