Python: list manipulation

I have a list of L objects (what does it stand for in scons). I would like to create two lists L1 and L2 , where L1 is L with the added element I1 , and L2 is L with the added element I2 .

I would use append , but that changed the original list.

How can I do this in Python? (sorry for the initial question, I do not use the language much, only for scons)

+4
source share
3 answers
 L1 = L + [i1] L2 = L + [i2] 

This is probably the easiest way. Another option is to copy the list and then add:

 L1 = L[:] #make a copy of L L1.append(i1) 
+8
source
 L1=list(L) 

duplicates the list. I think you can figure out the rest :)

+3
source

You can make a copy of your list

 >>> x = [1, 2, 3] >>> y = list(x) >>> y.append(4) >>> y [1, 2, 3, 4] >>> z = list(x) >>> z.append(5) >>> z [1, 2, 3, 5] 

or use concatenation that will make a new list

 >>> x = [1, 2, 3] >>> y = x + [4] >>> z = x + [5] >>> y [1, 2, 3, 4] >>> z [1, 2, 3, 5] 

The former is probably more moving idiomatic / general, but the latter works just fine in this case. Some people also copy using truncation ( x[:] creates a new list with all the elements of the original x list) or the copy module. None of them are terrible, but I find the former to be mysterious and the latter a little stupid.

+2
source

Source: https://habr.com/ru/post/1308163/


All Articles