1

I was reading about how to declare a matrices in python and I find this question How to define two-dimensional array in python

It's work with me, but I understanding what was done here in part, what I don't understanding is the parameter before the "for" in both loops...So I going to my terminal and testing parts of this for one by one, so when I type:

0 for x in range(w):

I receive:

File "< stdin >", line 1

So I try:

[0 for x in range(w)] for y in range(h):

receive:

File "< stdin >", line 1 [0 for x in range(w)] for y in range(h):

So I try:

[0 for x in range(w)]

and

[[0 for x in range(w)] for y in range(h)] 

and it's work...

So why the loop works when I put the brackets and not work without the brackets?

Thanks in advance.

2

3 Answers 3

1

It is list comprehension in python. And similar, there is also set comprehension, dict comprehension. It uses the elements in for loop to construct the list. Such as

>>> [2*i for i in range(10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> [i for i in range(10) if i % 2 == 1]
[1, 3, 5, 7, 9]
>>> [0 for _ in range(10)]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> [[i for i in range(j)] for j in range(5)]
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
>>> {i : chr(65+i) for i in range(5)}
{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}

  1. https://www.python.org/dev/peps/pep-0202/
  2. https://www.python.org/dev/peps/pep-0274/
Sign up to request clarification or add additional context in comments.

Comments

1

You need the brackets so that the python interpreter processes the operations within the brackets in the correct order. Otherwise, the statement is not being interpreted correctly.

Comments

0

You are looking at a list comprehension(please look over 5.1.4. Nested List Comprehensions of the link). The same task may be achieved using generator expression which does not involve brackets, but a generator does not create a list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.