How to copy list of lists from python without last elements from each list

Question:

How can I copy list of lists and delete last element from each in one step ? I can do something like this, but would like to learn to do it in one step:

test2 = [["A","A","C"],
         ["C","A"],
         ["A","B","C","A"]]

import copy
test3 = copy.deepcopy(test2)
for item in test3:
    del item[-1]
Asked By: ThomasJohnson

||

Answers:

In one step, you’ll want to use a list comprehension. Assuming your lists are two dimensional only and the sublists composed of scalars, you can use the slicing syntax to create a copy.

>>> [x[:-1] for x in test2]
[['A', 'A'], ['C'], ['A', 'B', 'C']]

If your sublists contain mutable/custom objects, call copy.deepcopy inside the expression.

>>> [copy.deepcopy(x[:-1]) for x in test2]
[['A', 'A'], ['C'], ['A', 'B', 'C']]
Answered By: cs95
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.