[Tutor] Append to list

Mats Wichmann mats at wichmann.us
Thu May 10 09:11:51 EDT 2018


On 05/09/2018 11:56 AM, 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):
>     print l
>     b.append(l)
>     l.pop(0)
> 
> print b

You've had some other comments, but let me add: sequence types in Python
don't work the way you seem to be expecting.

you can just loop over a sequence like a list directly. OR you can use
the range function to create a sequence, but you wouldn't do both.  In
the interpreter:

  >>> l = [1, 2, 3, 4]
  >>> for i in l:
  ...     print(i)
  ...
  1
  2
  3
  4
  >>> for i in range(1, 5):
  ...     print(i)
  ...
  1
  2
  3
  4
  >>>


Python provides syntax called a list comprehension that lets you build a
list on the fly, rather that writing out a loop with an append inside
it, at first it looks a little strange but it soon becomes very
comfortable (life will *really* get better if you stop using
single-character variable names that look alike!):

  >>> l = [1, 2, 3, 4]
  >>> b = [i for i in l]
  >>> print(b)
  [1, 2, 3, 4]
  >>>


More information about the Tutor mailing list