How to return list of lists

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Apr 25 14:36:58 EDT 2013


On Thu, 25 Apr 2013 08:01:09 -0700, eternaltheft wrote:

> Hi guys, I'm having a lot of trouble with this.
> 
> My understanding of python is very basic and I was wondering how I can
> return this table as a list of lists.
> 
> 1	2	3	4	5
> 3	4	5	6
> 5	6	7
> 7	8
> 9


Do you know how to build lists of numbers?

a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6]
c = [5, 6, 7]
d = [7, 8]
e = [9]


Now put them in a list:

table = [a, b, c, d, e]
print table


Got that so far? Now let's see how you might do the same thing without 
typing up the inner lists by hand. For that, you want the range() 
function.

a = range(1, 6)  # 1 is included, 6 is excluded.
b = range(3, 7)
c = range(5, 8)
# etc.


Now let's do it without the temporary variables a, b, c, d, e.

This time, start with the outer list, only with nothing in it. Then fill 
it using the range function.

table = []
table.append(range(1, 6))
table.append(range(3, 7))
# etc.


Now let's put this in a function:


def table(n):
    # Returns a triangular table (list of lists).
    # So far, we ignore n and hard-code the table. We'll fix this later.
    table = []
    table.append(range(1, 6))
    table.append(range(3, 7))
    # etc.
    return table


You're about halfway there now. The easy half. You get to do the hard 
half :-)


You need to think about how to turn a series of repeated appends into a 
loop, either a while loop or a for loop. I recommend you use a for-loop. 

Start by answering these questions:

* if the argument to the function, n, is 4, how many rows and how many 
columns will the table have?

* if n is 5, how many rows and columns will the table have?

* in general, for some value of n, what will be the first row?

* turn that into a call to range. Remember that if you call range with 
two arguments, the first argument is included, the second is excluded:
range(5, 9) => [5, 6, 7, 8]

* what will the second row be? Hint: the *first* number in the second row 
will be the first number of the first row PLUS TWO; the *last* number in 
the second row will be ... what?

* turn that into a call to range. Can you see the pattern for how each 
call to range will vary from the last?

* this suggests you want a for loop:

for row number 1, 2, 3, ... 
    table.append(make a row)

Obviously that's not real Python code. You need to write the Python code.


Write some code, and if you run into trouble, come back and ask for help.



Good luck! 


-- 
Steven



More information about the Python-list mailing list