Can this be reduced to a single line (after assigning a
)?
a = [1,2,3]
b = a[:]
b.append(4)
You can use the sequence method list. extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values. So you can use list. append() to append a single value, and list.
For a list, += is more like the extend method than like the append method. With a list to the left of the += operator, another list is needed to the right of the operator. All the items in the list to the right of the operator get added to the end of the list that is referenced to the left of the operator.
The following is probably the simplest:
b = a + [4]
Here, you don't need a[:]
since we're no longer copying the reference (+
creates and returns a new list anyway).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With