1

So, I'm thinking of creating a 2D array where row represents city names (in integers of course) and column representing temperature.

days = int(input("Enter days: "))
city = int(input("Enter city: "))
array = [[0]* days]*city
i = 0

printing the array with input:

days = 3
city = 3

gives me something like:

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

but the problem I'm having now is, how to insert values into the array?

when i was working on 1D array, i used:

while i<days:
    array[i] = int(input("temperature: "))
    i+=1

which inserts the temperature into the array.

array = [1,2,3]

but now that it's 2D, I can't seem to figure it out. The rows now represent the city and the column represents the temperature. I want to have something like.

[[1,2,3],[4,5,6],[7,8,9]]

How would I modify my while loop to implement 2D arrays?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Electric
  • 517
  • 11
  • 25
  • Possible duplicate of [How to input matrix (2D list) in Python?](https://stackoverflow.com/questions/22741030/how-to-input-matrix-2d-list-in-python) – Georgy Jul 12 '19 at 09:28

2 Answers2

3

To go over a 2D array you have to use two nested loops.

i = 0
j = 0
while (i < len(array)):
    while(j < len(array[i]):
        array[i][j] = value
        j = j + 1
    j = 0
    i = i + 1

Those loops set in a 2D array each time value. value can be in this case whatever you want it to be. The first index determines the array in the array and the second index selects the value in the nested array. In your case when you have [[1, 2, 3], [4, 5, 6], [7, 8, 9]], array[1][2] == 6

This also works for arrays that are not symmetric.

Erik
  • 153
  • 8
2

Oups! Lists are mutable objects in Python, and a list contains reference to objects. So when you write array = [[0]* days]*city, the external list contains city pointers to an unique list initialized with days 0.

Demo:

>>> array = [[0]* 3]*3
>>> array[0][0] = 1
>>> array
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

You should write instead array = [ [0] * 3 for i in range(3)]

Demo:

>>> array = [ [0] * 3 for i in range(3)]
>>> array[0][0] = 1
>>> array
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

For your question just cascade loops:

for c in range(city):
    for day in range(days):
        array[c][day] = int(input("temperature: "))
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252