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]
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']]
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]
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']]