Posts: 8
Threads: 3
Joined: Jan 2019
Hi,
I need some help with the appending of the values into the 2D array using a FOR loop. I am ok with printing the values, its the append that I need help with:
Array=[[100,20],[90,29],[102,89],[2,2]]
for row in Array:
print ("Row Values:", row)
for col in row:
print ("column values:",col)
Array1=([],[],[],[])
for i in Array1:
for i in range (4):
N1=input("Enter Number 1:")
Array1[i].append(N1)
for j in range(4):
N2=input("EnterNum ber 2:")
Array1[i].append(N2)
print (Array)
Posts: 817
Threads: 1
Joined: Mar 2018
Since lists are mutable objects, you can change them in place, e.g.
Array=[[100,20],[90,29],[102,89],[2,2]]
for row in Array:
row.append('New value') So, each list in Array was appended with string 'New value'.
print(Array) Output: [[100, 20, 'New value'],
[90, 29, 'New value'],
[102, 89, 'New value'],
[2, 2, 'New value']]
Posts: 8
Threads: 3
Joined: Jan 2019
(Mar-18-2019, 01:04 PM)scidam Wrote: Since lists are mutable objects, you can change them in place, e.g.
Array=[[100,20],[90,29],[102,89],[2,2]]
for row in Array:
row.append('New value') So, each list in Array was appended with string 'New value'.
print(Array) Output: [[100, 20, 'New value'],
[90, 29, 'New value'],
[102, 89, 'New value'],
[2, 2, 'New value']]
thank you that worked great, now I want to remove an item and this code doesn't seem to work:
Array=[[100,20],[90,29],[102,89],[2,2]]
print (Array)
N1=int(input("Enter a number to delete"))
for row in Array:
if row == N1:
Array.remove(N1)
print (Array)
Posts: 817
Threads: 1
Joined: Mar 2018
Mar-24-2019, 10:57 AM
(This post was last modified: Mar-24-2019, 10:57 AM by scidam.)
row in your loop is of type list, so comparison of an int and a list always leads to false, and .remove is not invoked.
Your code should be something like this:
for row in Array:
if N1 in row:
# uncomment what you need
# row.remove(N1) # remove the value from the row, and therefore from the original Array consisting of such rows
# Array.remove(row) # remove entire row from the array Nevertheless, deleting items from an array
that is being under iterations is not a good practice; so, you can create another one and fill it with rows based on the condition.
Posts: 8
Threads: 3
Joined: Jan 2019
great, that is perfect! thank you!
|