Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple lists in Python

Tags:

python

list

I have this part of a code:

def readTXT():
    part_result = []
    '''Reading all data from text file'''
    with open('dataset/sometext.txt', 'r') as txt:
        for lines in txt:
            part = lines.split()
            part_result = [int(i) for i in part]
            #sorted([(p[0], p[14]) for p in part_result], key=lambda x: x[1])
            print(part_result)
            return part_result

And I'm trying to get all lists as a return, but for now I'll get only the first one, what is quite obvious, because my return is inside the for loop. But still, shouldn't the loop go through every line and return the corresponding list?

After doing research, all I found was return list1, list2 etc. But have should I manage it, if my lists will be generated from a text file line by line?

It frustates me, not being able to return multiple lists at once.

like image 226
Viktoria Avatar asked Dec 11 '25 15:12

Viktoria


1 Answers

Here's my suggestion. Creating a 'major_array' and adding 'part_result' in that array on each iteration of loop. This way if your loop iterates 10 times, you will then have 10 arrays added in your 'major_array'. And finally the array is returned when the for loop finishes. :)

def readTXT():
    #create a new array
    major_array = [] 
    part_result = []
    '''Reading all data from text file'''
    with open('dataset/sometext.txt', 'r') as txt:
        for lines in txt:
            part = lines.split()
            part_result = [int(i) for i in part]
            #sorted([(p[0], p[14]) for p in part_result], key=lambda x: x[1])
            print(part_result)
            major_array.append(part_result)
         return major_array
like image 131
Muhammad Hamza Javed Avatar answered Dec 13 '25 04:12

Muhammad Hamza Javed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!