[Tutor] Final review

Steven D'Aprano steve at pearwood.info
Thu May 1 14:30:01 CEST 2014


On Wed, Apr 30, 2014 at 10:21:41PM -0700, Scott W Dunning wrote:

> So, I get a little confused about lists sometimes.  This one is a 
> little hard to make heads or tails of.  I get confused about how to 
> tell how many lists are within one list like the one below.  How many 
> lists are located inside alist is it 1 or 2, 3??  Also, do spaces 
> count as an index in lists?
> 
> >>> alist = [3, 67, "cat”, [56, 57, “dog”], [], 3.14, False]
> >>> print alist[4:]
> [[], 3.14, False]

Spaces do not count as indexes. Spaces are just inserted when printing 
the list to make it easier for people to read. It is commas, not spaces, 
which separate items in the list. So you have:

alist = [3, 67, "cat", [56, 57, "dog"], [], 3.14, False]

Count the items separated by commas:
3 comma  <== that's one
67 comma  <== that's two
"cat" comma  <== three

Next is tricky: the square bracket [ starts a new list. Since we don't 
care how many items are inside that list, we just keep going until we 
reach a matching ] closing square bracket:

[56, 57, "dog"] comma  <== that's four
[] comma  <== five
3.14 comma  <== six
False  <== seventh and last

Notice that because the commas *separate* items, there is one more item 
than separators:  1,2,3,4,5,6,7  (six commas and seven items).

Also notice that out of the seven items inside alist, only two of 
them are lists:

3  INTEGER
67  INTEGER
"cat"  STRING
[56, 57, "dog"]  LIST with three items
[]  LIST with zero items
3.14  FLOAT
False  BOOLEAN FLAG


> The ouput for below is 2 when it seems like there should be 3 lists 
> located inside x.  Is it [10,20] that is not consider inside of x?  
> Any tips on how to tell how to spot them more clearly?
> 
> x = ['a', [2.0, 5, [10, 20]]]
> print len(x)

Again, look at the commas:

'a' (a string) comma  <== first item

The next item begins with a square bracket, so it is a list. We ignore 
everything inside it *except more square brackets* until we reach the 
matching square bracket:

[2.0 comma (but we don't care)
 5 comma (still don't care)
 [  (and now we start yet another list, inside a list inside a list!)
  10 comma (don't care)
  20 (don't care)
  ]  (we have reached the end of the innermost list)
 ]  (we have reached the end of the inner list

and no more items after that. So the list called "x" has two items:

- the string "a"
- a list containing 2.0, 5, and another list


So there are two items inside list "x", three items inside the list 
inside "x", and two items inside the list inside that.

When in doubt, this may help make it more obvious:

x = ['a', [2.0, 5, [10, 20]]]
for item in x:
    print(item)


That will show you each item in turn.


-- 
Steven


More information about the Tutor mailing list