The Student Room Group

2D Lists

I'm trying to learn python (mainly because I have an exam coming up in it soon!) and I don't understand what 2D lists are in python. My teacher's explanation doesn't make sense to me!
A "2D list" is just a list-of-lists. In other words, it's a list, but each item nested within that list is also a list. For example, here's a 2D list of names:

names = [
[ "Margaret", "John", "Tony", "David", "Theresa" ],
[ "Fred", "Barney", "Wilma", "Betty" ],
[ "Robb", "Eddard", "Jon", "Arya", "Sansa", "Brann" ]
]


https://repl.it/repls/EllipticalGlassSystemsoftware

The main thing to remember ... What's the difference between a "1D list" and a "2D list"? answer -- absolutely nothing!! A "list of lists" is still just a list.

Some people describe 2D lists as being like a 'grid' or 'excel table', where you're dealing with a series of rows and columns. (Note, it doesn't matter which dimension is 'row' or which one is 'column') -- this is a very good/close analogy, but "slightly" imperfect because unlike a grid, the 'inner dimensions' do not need to be uniform - as above, there are 3 lists held inside a list. The first list has a length of 5, the second has a length of 4, and the third list has a length of 6.

So, the above 2D list is a bit like a table , but if you were to draw it on paper (assuming that the inner dimension is a row rather than a column, just for the sake of argument), then it'd be like a "jagged" table with some rows sticking out further than the others.

But of course, you can use a 2D list like a uniform grid/table too if you want to -- all you'd have to do to get a grid is make sure the 'inner' ('nested') lists are all the same length as each other.

And finally - don't try to over-think it. Make sure you are 100% comfortable with plain 1D lists first though; if you understand the concepts of a 1D list, then there's actually no difference when it comes to 2D lists. -- http://greenteapress.com/thinkpython2/html/thinkpython2011.html
(edited 5 years ago)

Quick Reply

Latest

Trending

Trending