Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy list and append an element in one line

Tags:

python

Can this be reduced to a single line (after assigning a)?

a = [1,2,3]
b = a[:]
b.append(4)
like image 617
user1002973 Avatar asked Jan 26 '13 13:01

user1002973


People also ask

How do you append multiple items to a list in Python in one line?

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.

Can you use += to append a 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.


1 Answers

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).

like image 166
NPE Avatar answered Oct 22 '22 05:10

NPE