DEV Community

sunmathi
sunmathi

Posted on

Mastering Python Essentials: File Handling, Lambda Functions, and Functional Programming

Introduction

  • Highlight the importance of Python as a versatile programming language.
  • Introduce the core topics: File handling, lambda functions, and functional programming techniques like map and filter.

Section 1: File Handling in Python

Basics of File Handling

  • Python offers easy-to-use methods for reading and writing files.
  • Modes:
    • r for reading
    • w for writing
    • a for appending

Example: Reading and Writing Files

# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, Python!")

# Reading from a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
Enter fullscreen mode Exit fullscreen mode

Section 2: Lambda Functions

What is a Lambda Function?

  • Anonymous, inline functions defined with the lambda keyword.
  • Syntax: lambda arguments: expression

Example Usage

  1. Single Line Functions:
   add = lambda x, y: x + y
   print(add(2, 3))  # Output: 5
Enter fullscreen mode Exit fullscreen mode
  1. Sorting with Lambda:
   items = [("apple", 2), ("banana", 1), ("cherry", 3)]
   sorted_items = sorted(items, key=lambda item: item[1])
   print(sorted_items)
Enter fullscreen mode Exit fullscreen mode

Section 3: Functional Programming with map and filter

The map Function

  • Applies a function to every item in an iterable.
  • Example:
  numbers = [1, 2, 3, 4]
  squares = list(map(lambda x: x ** 2, numbers))
  print(squares)  # Output: [1, 4, 9, 16]
Enter fullscreen mode Exit fullscreen mode

The filter Function

  • Filters elements of an iterable based on a condition.
  • Example:
  numbers = [1, 2, 3, 4, 5]
  evens = list(filter(lambda x: x % 2 == 0, numbers))
  print(evens)  # Output: [2, 4]
Enter fullscreen mode Exit fullscreen mode

Conclusion

  • Python's file handling, lambda functions, and functional programming tools like map and filter empower developers to write efficient, concise, and elegant code.
  • These concepts form the backbone of many advanced Python applications.
  • Practice these techniques regularly to strengthen your understanding and apply them effectively in your projects.

Top comments (0)