Eric_S
Eric_S

Reputation: 21

I want to understand how multi dimensional lists work in python

I am just starting to learn python and was looking for a solution to build a multi dimensional list. I found the solution below on this site and it works but I want to understand why it works.

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

I understand how loops work, and get how to print or do some calculations under a for loop but here there's no : being used to tell the for loop to "do" something. My second question is how does the way this is written actually creates the output? Is this just built in to the language?

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Thanks in advance!

Eric

Upvotes: 0

Views: 52

Answers (2)

user4673965
user4673965

Reputation:

1.

The code you posted does the following:

To begin with, for x in range(4) means that whatever is before it is repeated four times. The fact that there is something before it means that colons are unnecessary, but this works only in lists. You could also try: [x for x in range(4)], which gives you [0, 1, 2, 3]. If you iterate on other lists, you could try:

words = ["Bob", "Jane", "House", "Cat"]
words_with_lengths = [[word, len(word)] for word in words]

This behavior also applies to other keywords, such as if. For example, you could do [x for x in range(10) if x > 6] (although that's stupid.)

By prepending a zero and wrapping that in brackets, a list is created. It thus creates a list with four zeroes (--> [0 for x in range(4)])

It then takes that four times (... for x in range(4)]), creating the list you linked.

2.

Anything that you type in the python console automatically prints output, given that it returns something.

This is different from python scripts. If you would run the code you posted from a script, you would actually not see any output since this behavior is not replicated in scripts.

Upvotes: 0

Malik Brahimi
Malik Brahimi

Reputation: 16721

This is known as a list comprehension, and you can dynamically populate a list without the use of append methods. In fact, this notation operates nearly as is written.

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

# 1. make 4 zeros, slap brackets around it
# 2. make 4 of these lists put it in a list

Upvotes: 2

Related Questions