can we append a list with another list in Python ?

Joshua Landau joshua.landau.ws at gmail.com
Tue Oct 23 05:38:23 EDT 2012


On 23/10/2012, inshu chauhan <insideshoes at gmail.com> wrote:
> can we append a list with another list in Python ? using the normal routine
> syntax but with a for loop ??

I assume you want to join two lists.

You are corrrect that we can do:

>>> start = [1, 2, 3, 4]
>>> end = [5, 6, 7, 8]
>>>
>>> for end_item in end:
>>>     start.append(end_item)
>>>
>>> print(start)
[1, 2, 3, 4, 5, 6, 7, 8]
>>>

However, it is markedly repetitive, no?
This is a common enough operation that there is a shortcut to find out about it.

If you want to find out what methods there are, try "help(...)". I
can't stress this enough.

>>> help(start)
Help on list object:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |
 |  Methods defined here:
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
...
 |  append(...)
 |      L.append(object) -- append object to end
...
 |  extend(...)
 |      L.extend(iterable) -- extend list by appending elements from
the iterable
...

So list.extend seems to do exactly this!

You can always check the documentation
<http://docs.python.org/tutorial/datastructures.html>.
An lo! The documentation says "start.extend(end)" is _equivilant_ to
"start[len(start):] = end".

Why?

Well, this uses the slicing syntax.

>>> start[:3]
[1, 2, 3]
>>> start[3:]
[4]
>>> start[2:3]
[3]

Wonderously, all these really say are "ranges" in the list. Hence, you
can "put" lists in their place.

"start[len(start):] = end" means "start[-1:] = end", so what you're
doing is saying "the empty end part of the list is actually this new
list". Hopefully that makes sense.

Finally, there is another method. Instead of *changing* the list, you
can make a new list which is equal to the others "added" together.

>>> new = start + end

_______________________________________________

Theses methods all have their own upsides. If you want to change the
list, use .extend(). If you want to change the list, but by putting
the new list somewhere inside the "old" one, use slicing:

>>> start = [1, 2, 3, 4]
>>> end = [5, 6, 7, 8]
>>>
>>> start[2:2] = end
>>> print(start)
[1, 2, 5, 6, 7, 8, 3, 4]

Looping is good for when you want to generate the extra items as you go along.

Finally, if you want to keep the old list or use these "inline", use "+".

_______________________________________________

Note that, being in the unfortunate position of "away from an
interpreter", none of my examples are copy-pastes. Hence they may be
wrong :/

# Not checked for errors, typos and my "friends" messing with it.



More information about the Python-list mailing list