how to insert the elements in a list properly?

length power elearn2014 at gmail.com
Wed Apr 9 09:09:37 EDT 2014


words = ["x1", "x2", "x3", "x4", "x5"]
words.append(words.pop(2))
words.append(words.pop(2))
words
['x1', 'x2', 'x5', 'x3', 'x4']
why i can't write it as:

[words.append(words.pop(2)) for i in range(0,2)]

>>> [words.append(words.pop(2)) for i in range(0,2)]
[None, None]


2014-04-09 18:46 GMT+08:00 Peter Otten <__peter__ at web.de>:

> length power wrote:
>
> > word=["x1","x2","x3","x4","x5"]
> > w=word[-2:]
> > del word[-2:]
> > word.insert(2,w)
> > word
> > ['x1', 'x2', ['x4', 'x5'], 'x3']
> >
> > what i want to get is
> > ['x1', 'x2', 'x4', 'x5', 'x3']
> >
> > how can i insert them ?
>
> Make the left-hand side an empty slice:
>
> >>> words = ["x1", "x2", "x3", "x4", "x5"]
> >>> w = words[-2:]
> >>> del words[-2:]
> >>> words[2:2] = w
> >>> words
> ['x1', 'x2', 'x4', 'x5', 'x3']
>
> Or note that the operation is equivalent to moving the third item to the
> end:
>
> >>> words = ["x1", "x2", "x3", "x4", "x5"]
> >>> words.append(words.pop(2))
> >>> words
> ['x1', 'x2', 'x4', 'x5', 'x3']
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140409/0c6c61d5/attachment.html>


More information about the Python-list mailing list