[Tutor] Append to list

Steven D'Aprano steve at pearwood.info
Wed May 9 19:46:17 EDT 2018


On Wed, May 09, 2018 at 10:56:45AM -0700, Rick Jaramillo wrote:
> 
> Hello,
> 
> I’m having trouble understanding the following behavior and would greatly appreciate any insight. 
> 
> l = [1,2,3,4]
> b=[]
> 
> for i in range(l):

That's not actually your code, is it? Because range(l) gives a 
TypeError. In future, please copy and paste your code, don't retype it 
from memory.

>     print l
>     b.append(l)
>     l.pop(0)

You are appending the same list each time, not a copy. Instead make a 
copy by taking a slice from the current position to the end of 
the list:

for i in range(len(l)):
    b.append(l[i:])

print b


will do what you want.



-- 
Steve


More information about the Tutor mailing list