Python Forum

Full Version: 2D arrays and appending values using a loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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) 
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']]
(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)
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.
great, that is perfect! thank you!