Xcecution
Xcecution

Reputation: 1117

Print an array with lists as elements

I started creating an array, then i referenced its element with lists. Now I want to print the entire array (this is: all the lists on the array), i created a function "show" and "show array" but always print the last element of the array

IN:

class Test:
    pass

def read(v, r):
    n = len(v)
    for i in range(0, n):
        v[i] = r
        v[i].number= 5+i
        v[i].name = i*2
        v[i].author = i+6
        v[i].genre = i*3
        v[i].quantity = i+2


def show_array(v):
    n = len(v)
    for i in range(0, n):
        show(v[i])


def show(reg):
    print(reg.number, end=' ; ')
    print(reg.name, end=' ; ')
    print(reg.author, end=' ; ')
    print(reg.genre, end=' ; ')
    print(reg.quantity)

def menu():

    v = 2 * [None]


    t= Test()
    read(v, t)

    show_array(v)


menu()

OUT:

6 ; 2 ;  7 ;  3 ;  3
6 ; 2 ;  7 ;  3 ;  3

Upvotes: 0

Views: 123

Answers (3)

RAVI507
RAVI507

Reputation: 129

I am not a python expert but u can try to make use of isinstance() this may help you to print all the values of a specified list by comparing the array value with list.If it is a list then print that particular list elements.If it is not a list then print the normal array value.

https://infohost.nmt.edu/tcc/help/pubs/python/web/isinstance-function.html

Upvotes: 0

huang
huang

Reputation: 519

Because this is only one t. First value is always coverd by last value.

You can write "print (v[i].name)" in "for" of "read()" and you can see the diffrence. You should create a new t.

Upvotes: 0

Emil Vikström
Emil Vikström

Reputation: 91983

No, you are showing all elements of the array. They are all pointing to the same object so when you alter the object in your read loop, you change the object everywhere. You need to create a new Test object for each place in your array.

Upvotes: 2

Related Questions