1

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]
ThomasJohnson
  • 167
  • 1
  • 10

1 Answers1

2

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']]
cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    Note, `deepcopy` has a default deepcopy behavior for custom classes. It is overridable with the `__deepcopy__` hook, but isn't strictly required (and in my experience, rarely necessary toimplement) – juanpa.arrivillaga Feb 13 '18 at 22:30
  • @juanpa.arrivillaga Okay, thank you. I was under the impression it'd throw errors. – cs95 Feb 13 '18 at 22:32