faqts : Computers : Programming : Languages : Python : Common Problems : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 4 people (50%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

How do I extend a list and assign it to a variable in one go?

Feb 20th, 2002 04:34
Steve Holden, Andy Stenger,


This isn't as easy as it looks, but it can be done. The main problem is 
that the list append() method doesn't return a value, but simply 
updates the list in place. So what you have to do is use multiple 
assignment, like this:
    origlst = [1, 2, 3]
    newlst = origlst = origlst + ["extra"]
After this assignment, both newlst and origlst refer to the same four-
element list. Beware, of course, because lists are mutable. If you 
change the list (for example, by altering one of its elements or 
deleting it) then the value accessed by both variables will change!
If you know about augmented assignment you might expect
    newlst = origlst += ["extra"]
to work, but unfortunately this is a syntax error.