I am just starting to learn python and was looking for a solution to build a multi-dimensional list. I want to understand how it works.


Code:
>>> list = [[0 for x in range(4)] for x in range(4)]


And also, how does the way this (below code) is written actually creates the output? Is this just built into the language?




Code:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]



Any help will be appreciated!
Multidimensional lists in pure Python are lists-of-lists. For a two-dimensional list a, e.g., a[0] is a list, a[1] is a list, and a[1][0] is an element. Your example creates a 4-element list where each element is also a 4-element list, functionally giving you a 4x4 2D list (although it's sort of up to you to interpret that as a 4x4 array; the language doesn't really know anything about that). The thing you've used there ([f(x) for x in iterable]) is called a "list comprehension", and is indeed a feature of the Python language. You can even use it to apply a function to every element of a list. For example, this will square the numbers from 0 to 9:

Code:
a = range(10)
squares = [element * element for element in a]


If you're writing Python on a computer, and having big arrays on which you can perform fast math is important to you, numpy is a good solution to explore.
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement