About python while statement and pop()

Steven D'Aprano steve at pearwood.info
Thu Jun 12 01:43:42 EDT 2014


On Wed, 11 Jun 2014 21:56:06 -0700, hito koto wrote:

> I want to use while statement,
> 
> for example:
>>>> def foo(x):
> ...     y = []
> ...     while x !=[]:
> ...         y.append(x.pop())
> ...     return y
> ...
>>>> print foo(a)
> [[10], [5, 6, 7, 8, 9], [1, 2, 3, 4]]
>>>> a
> []   but this is empty
>>>> so,I want to leave a number of previous (a = [[1, 2, 3, 4],[5, 6, 7,
>>>> 8, 9],[10]])


I wouldn't use a while statement. The easy way is:

py> a = [[1, 2, 3, 4],[5, 6, 7, 8, 9],[10]]
py> y = a[::-1]
py> print y
[[10], [5, 6, 7, 8, 9], [1, 2, 3, 4]]
py> print a
[[1, 2, 3, 4], [5, 6, 7, 8, 9], [10]]

If you MUST use a while loop, then you need something like this:


def foo(x):
    y = []
    index = 0
    while index < len(x):
        y.append(x[i])
        i += 1
    return y


This does not copy in reverse order. To make it copy in reverse order, 
index should start at len(x) - 1 and end at 0.



-- 
Steven



More information about the Python-list mailing list