How to make a list of lists using for loops in python?

I am new to python and I want to create a list of lists.

student_details.txt contains data like:

101 Rahul
102 Julie
103 Helena
104 Kally

      

CODE

lis = []

with open("student_details.txt" , "r+") as f:    
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)

      

Conclusion I want

[[101, Rahul], [102, Julie], [103, Helena], [104, Kally]]

The output i m gets

['101', 'Rahul', '102', 'Julie', '103', 'Helena', '104', 'Kally']

+3


source to share


5 answers


Your code:

lis = []

with open("student_details.txt" , "r+") as f:    
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)

      

Notice the two for looping: what you are doing is looping through each line, then through each element of that line. Then you insert each item into your list lis

. To get the desired result, you want the list to move through the list of two items on each line. In fact, you are already creating this list of items with f.read().split()

, so you just need to add that. This will result in the following:



lis = []

with open("student_details.txt" , "r+") as f:    
    for i in range(1,3,1):
        #no second loop here
        data = f.read().split()
        lis.append(data)
print(lis)

      

This still doesn't give us the right answer, the problem here is the loop, we can fix that by simply reading each line ideotically, without specifying any ranges:

lis = []

with open("student_details.txt" , "r+") as f:    
    for line in f:
        #no second loop here
        data = line.split()
        lis.append(data)
print(lis)

      

0


source


You can read line by line, iterate over a descriptor or with readlines()

, split each line, append each result, etc. Fixing the code would require removing the loop range

that simply reads the file 3 times (but only effectively reads once the first time) and adds the delimited line items using a list comprehension to be more pythonic:

with open("student_details.txt" , "r+") as f:    
     lis = [line.split() for line in f]

      

note that the cool thing about line.split()

(no parameters) is that it is automatically stripped of the line terminator.



but you can make it easier: the module csv

does all the parsing for you:

import csv
with open("student_details.txt" , "r") as f:
   cr = csv.reader(f,delimiter=" ")
   # iterate on rows and generate list of lists:
   result = list(cr)

      

+3


source


You can split along lines:

lis = []

with open("student_details.txt" , "r+") as f:    
    for line in f:
       data = line.split()
       lis.append(data)
print(lis)

      

Result:

[['101', 'Rahul'], ['102', 'Julie'], ['103', 'Helena'], ['104', 'Kally']]

      


Or in a more compact way:

with open("student_details.txt" , "r+") as f:    
    lis = [line.split() for line in f]
print(lis)

      

Result:

[['101', 'Rahul'], ['102', 'Julie'], ['103', 'Helena'], ['104', 'Kally']]

      

+1


source


The easiest way is to do it with an list

understanding like this:

with open("student_details.txt" , "r+") as f:
    lis = [line.split() for line in f]

      

or if you want loop

, you can loop

through the file without reading it:

with open("student_details.txt" , "r+") as f:    
    lis = []
    for line in f:
        lis.append(line.split())

      

+1


source


You can also try this alternative. I am using splitlines () method.

data = []
f = open('student_details.txt', 'r')
for line in f.read().splitlines():
    data.append([line])
print(data)

      

0


source







All Articles