4

I have a list L of objects (for what it's worth this is in scons). I would like to create two lists L1 and L2 where L1 is L with an item I1 appended, and L2 is L with an item I2 appended.

I would use append but that modifies the original list.

How can I do this in Python? (sorry for the beginner question, I don't use the language much, just for scons)

3 Answers 3

8
L1 = L + [i1]
L2 = L + [i2]

That is probably the simplest way. Another option is to copy the list and then append:

L1 = L[:]       #make a copy of L
L1.append(i1)
Sign up to request clarification or add additional context in comments.

Comments

3
L1=list(L)

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

Comments

2

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, which 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 a touch more idiomatic/common, but the latter works fine in this case. Some people also copy using slicing (x[:] makes a new list with all the elements of the original list x referred to) or the copy module. Neither of these are awful, but I find the former a touch cryptic and the latter a bit silly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.