Python Forum
2D arrays and appending values using a loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
2D arrays and appending values using a loop
#1
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) 
Reply
#2
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']]
Reply
#3
(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)
Reply
#4
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.
Reply
#5
great, that is perfect! thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  loop function that parses arrays with condition: no redundant data amela 4 2,290 Nov-05-2020, 07:29 PM
Last Post: amela
  How can I run a function inside a loop every 24 values of the loop iteration range? mcva 1 2,131 Sep-18-2019, 04:50 PM
Last Post: buran
  Issues with Inserting Values into an Empty List with a While Loop TommyMer 2 3,761 Sep-12-2018, 12:43 AM
Last Post: TommyMer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020