A single variable in Python can accommodate values of various data types, and if we need to collect multiple data elements within a single variable, Python provides the option of using a list.
Lists are created using squared brackets in Python. The following is the syntax to create a list:
MyList = ["apple", "mango", "banana"]
The following are some important features of lists in Python:
Multiple data types: Lists can contain items of different data types.
Changeable: We can update, add, and delete items in a list.
Ordered: List items are ordered, which means that when we add a new item to the list, it will be added to the end of the list.
Indexed: List items are indexed, which means that the first item will have an index of 0, the second item will have an index of 1, and so on.
Duplicates: Since every item has its own unique index in a list, we can have duplicate entries.
Let’s now understand how to read a file line by line into a Python list using the following two methods:
Learnfromeducative
This code opens the file.txt
file. It then iterates through the lines in the file and stores each line as an element in the Lines1
list. The result is a list of strings, where each string represents a line from the file. The print(Lines1)
statement will display the lines with newline characters.
It preserves the newline characters, which can be useful if we want to maintain the original formatting of the file when writing it back later.
It allows us to distinguish between empty lines (lines containing just a newline character) and lines with no content.
# Method 2:# Open the file and store the elements line by line in a list# and also removing the newline characters:with open('file.txt') as FileContent:Lines2 = [line.rstrip() for line in FileContent]print(Lines2)
This code again opens the file.txt
file. However, this time, it uses the rstrip()
method to remove any trailing whitespace characters, including newline characters (\n
), from each line before storing it in the Lines2
list. As a result, the Lines2
list contains the same lines as in Lines1
, but without the newline characters at the end of each line. The print(Lines2)
statement will display the lines without newline characters.
It removes newline characters, which can make the data easier to work with when processing it line by line.
It’s suitable for scenarios where we want to treat each line as a distinct string without any trailing whitespace.
Free Resources