coding girl
coding girl

Reputation: 183

How do I structure out this for loop?

I have this line of code that I'd like to use for another function:

array=[[0 for column in range(width)] for row in range(height)]

How do I separate the for statement? I tried this:

    column = 0
    for row in range(height):
        row = 0
        array = [column[row]]
        return array

The output should be a list of lists with 0 as their elements.

Upvotes: 0

Views: 53

Answers (3)

Guy
Guy

Reputation: 50909

How about

array = [[0] * width] * height

This will create list of lists initialized with 0s

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

Edit

This will create N copies of the same list, so any change will affect all the lists. If you do want to update values use

array = [[0] * width for _ in range(height)]

Same results, but now there are N different lists.

Upvotes: 1

Andrey Fedorov
Andrey Fedorov

Reputation: 9699

You're going to need to define the array variables explicitly, i.e.

rows = []
for row in range(height):
    column = [0] * width
    rows.append(column)

Upvotes: 0

vonludi
vonludi

Reputation: 429

You could try this

array = []
for row in range(height):
  array.append([0 for column in range (width)])

Upvotes: 1

Related Questions