[Tutor] Help!
Alan Gauld
alan.gauld at yahoo.co.uk
Fri Sep 11 04:46:43 EDT 2020
On 11/09/2020 07:41, Dennis, Lauren wrote:
> how to create a two dimensional list using a for loop and range() function.
Note that python, unlike some other languages, such as Pascal,
does not directly support multidimensional lists. Instead you
must construct a list of lists (of lists of....)
So if you know how to construct a one dimensional list you know
how to construct multi dimensional lists too. Simply create
a list of lists:
list1D = [1,2,3]
list2D = [[1,2,3],[4,5,6],[7,8,9]]
Sometimes written as:
list2D = [
[1,2,3],
[4,5,6],
[7,8,9]
]
for clarity.
There are many ways to construct such lists, you want to
use a for loop and range. I suspect you may need two for
loops and two ranges. Here is how to construct a single
dimension list using a for/range combination:
mylist = []
for n in range(size):
mylist.append(n)
Which can be written in abbreviated form as:
mylist = [n for n in range(size)]
Now for 2D you just have to modify that so that
instead of appending n you append another list.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list