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.
-
Reading 5.1.3. List Comprehensions from the official docs explain this quite well. 5.6 Looping techniques might also be a good thing to skim over.Sash Sinha– Sash Sinha2020年12月14日 02:39:22 +00:00Commented Dec 14, 2020 at 2:39
1 Answer 1
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]
5 Comments
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.else, it's just a matter of re-ordering things (putting the for last). See my latest update.Explore related questions
See similar questions with these tags.