简体   繁体   中英

Python - Append Help - String & list

Another append question... This is my code:

def s(xs,n,m):
    t = []
    while n < m:
        n += 2
        t.append(xs[n])
    return t

When I evaluate the following:

x = s('African', 0, 3)

Why does it return this?:

['r', 'c']
while n < m:
    n += 2 # at this point n = 2 because you've passed 0
    t.append(xs[n]) # you append r to t since xs[2] = r

but n < m still, so next iteration:

while n < m:
    n += 2 # at this point n = 4
    t.append(xs[n]) # you append c to t since xs[4] = c

now n > m, so the function returns ['r', 'c'] . Everything is correct.

Ok, so line-by-line...

Your call looks like this:

x = s('African', 0, 3)

so what happens is:

  1. Step 1. - initial assignement

     def s(xs,n,m): 

    xs='African' , n=0 and m=3 and then:

     t = [] 

    (so, empty list t is introduced).

  2. Step 2. - loop

    1. Then the following condition is evaluated:

       while n < m: 

      to True , because 0 < 3 .

    2. And then n is increased:

       n += 2 

      so it is now equal to 2 .

    3. Then the appropriate element is appended to the empty t list:

       t.append(xs[n]) 

      and this element is " r ", because xs[2] == 'r' .

    4. Then n < m condition is again evaluated to True (because 2 < 3 ), so the loop executes again:

       n += 2 

      and n is now equal to 4 .

    5. Then appropriate char from xs string is appended to t list (which already has one element, r , as we mentioned above).

       t.append(xs[n]) 

      and this element is " c " (because xs[4] is exactly " c ").

    6. Then condition for while loop is again evaluated, but this time to False (because 4 < 3 is not true), so the loop stops executing...

  3. (Step 3. - after the loop) ...and the program flow goes to the final statement of the function, which is:

     return t 

And t returns the list we filled with two elements - as a result, the function returns list ['r', 'c'] .

Is it clear enough? Did it help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM