Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #69947 > unrolled thread

Re: how to insert the elements in a list properly?

Started bylength power <elearn2014@gmail.com>
First post2014-04-09 21:09 +0800
Last post2014-04-09 13:42 +0000
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: how to insert the elements in a list properly? length power <elearn2014@gmail.com> - 2014-04-09 21:09 +0800
    Re: how to insert the elements in a list properly? Dan Sommers <dan@tombstonezero.net> - 2014-04-09 13:42 +0000

#69947 — Re: how to insert the elements in a list properly?

Fromlength power <elearn2014@gmail.com>
Date2014-04-09 21:09 +0800
SubjectRe: how to insert the elements in a list properly?
Message-ID<mailman.9073.1397050789.18130.python-list@python.org>

[Multipart message — attachments visible in raw view] — view raw

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__@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
>

[toc] | [next] | [standalone]


#69948

FromDan Sommers <dan@tombstonezero.net>
Date2014-04-09 13:42 +0000
Message-ID<li3ip3$svo$1@dont-email.me>
In reply to#69947
On Wed, 09 Apr 2014 21:09:37 +0800, length power wrote:

> 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]

You can, but you don't want to.  At this point, even though the
comprehension returned something else, words contains what you want.

HTH,
Dan

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web