Creating, Writing, and Reading Lists

Python for Beginners: Delving Deep into Lists and File Operations

Introduction:

In the vast world of Python programming, understanding the nuances of lists and file operations can provide a significant boost to one's coding proficiency. Today, we dissect a straightforward Python program, shining a light on the intricacies of list manipulations and file handling.

1. Setting the Stage with Initial Data:



f = ['Andrew','Andy','Mary Elizabeth','Thomas']
l = ['Walker'] * len(f)
w = [200, 100, 135, 45]

The three lists initialized serve as the foundation for our dataset:

  • f represents first names.
  • l contains last names. The repetition of 'Walker' is achieved using Python's ability to multiply lists.
  • w holds the weights corresponding to each person.

2. Adding Data with a Function:


def add_person(first_name:str, last_name:str, weight:int):
    if isinstance(first_name, str) and isinstance(last_name, str) and isinstance(weight, int):
        f.append(first_name)
        l.append(last_name)
        w.append(weight)
    else:
        print("Invalid input data type")

This function, add_person, is crafted to add more data to our initialized lists. It expects three inputs: first name, last name, and weight. Type annotations, a feature in Python, hint at the expected data type for each parameter.

The isinstance() function checks the data type of the provided values, ensuring they match our expectations. If they do, the new data is appended to the respective lists. Else, a message alerts the user of an incorrect data type.

3. Storing Data in a File:


with open('people.txt', 'a+') as file:
    for i in range(len(f)):
        file.write(f[i] + ' ' + l[i] + ' weighs ' + str(w[i]) + ' pounds.\n')

Our next step is persisting the data. Using Python's open() function with the 'a+' mode, we both append to and read from the file 'people.txt'. The loop iterates over our lists, writing each person's full name alongside their weight.

4. Displaying Stored Data:


with open('people.txt', 'r') as file:
    for line in file:
        print(line)

Lastly, we read and display the content of 'people.txt'. Using the 'r' mode ensures the file is opened for reading. Each line of the file is then printed to the console, allowing for a quick verification of our stored data.

Conclusion:

Through this exploration, we've witnessed the synergy of lists and file operations in Python. Such foundational knowledge not only strengthens one's grasp of Python but also paves the way for more complex tasks in data management and processing. Keep coding and exploring! Google Colab Example

Comments

Popular posts from this blog

Drawing Tables with ReportLab: A Comprehensive Example

Blog Topics

DataFrame groupby agg style bar