1

I was trying to figure out how to populate an array with zeros and came across this solution that confused me.

col = 3
row = 3
A = [[0 for column in range(col)] for row in range(row)]

How come you can put a number next to a for loop and python will know to repeat that value within it? If I do:

0 for column in range(col) 

outside of the list it comes out as an error. Why is this?

Also how does adding a for loop work here? I thought the for loop format was like this:

for value in Something:
     #Repeating code

Why doesn't the solution follow this for loop format? If I did a for loop not in this format outside the list it comes out as an error.

1

1 Answer 1

3

The reason you get an error with 0 for column in range(col) is because this feature is known as a list comprehension and it's missing the [] "listness" :-)

What you would need is:

[0 for column in range(col)]

The basic idea is that [value for <some iteration function>] will give you a list of value items, as many as there are iterations of the iteration function.

And the reason that for works here is because it can be used in more than one way, in much the same way as you can use break within for or while loops, or if in list comprehensions as well:

>>> [x for x in range(20)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> [x for x in range(20) if x % 3 == 2]
[2, 5, 8, 11, 14, 17]

>>> [x if x % 2 == 0 else -x * 100 for x in range(10)]
[0, -100, 2, -300, 4, -500, 6, -700, 8, -900]
Sign up to request clarification or add additional context in comments.

5 Comments

Oh I see, so it's just a unique characteristic of working with lists. Would this work with things other than for loops?
@CKA, you would need something with a finite iteration count, I've never thought too much about it in all honestly. Given it's meant to be used with an iterable of some sort, I suspect for is the only way, though I don't discount the possibility of some dark corners of Python I don't know yet :-) I've added some code that shows you can use extra stuff, like an if filter.
Wow that's really interesting, thank you so much. Also just curious, if you can use an IF statement, could you also use an ELSE statement? I tried it in PyCharm and it doesn't seem like it's possible
@CKA: you can indeed use else, it's just a matter of re-ordering things (putting the for last). See my latest update.
Wow, absolutely blowing my mind here. Thanks again!

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.