Functions for Collections in Python

Overview

This lesson covers the various built-in functions Python provides for working with collections like lists, tuples, sets, and dictionaries. Understanding these functions allows you to perform common tasks on collections efficiently, such as calculating the length, finding the maximum and minimum values, and more.

Introduction

Python offers a set of built-in functions that can be applied directly to collections. These functions can significantly simplify the process of manipulating and querying data stored in collections.

Common Functions for Collections

  1. len(): Returns the number of items in a collection.
    • Usage: len(collection)
  2. max(): Returns the largest item in a collection.
    • Usage: max(collection)
  3. min(): Returns the smallest item in a collection.
    • Usage: min(collection)
  4. sum(): Calculates the sum of items in a collection. Only applicable to numerical data.
    • Usage: sum(collection)
  5. sorted(): Returns a new list containing all items from the collection in ascending order.
    • Usage: sorted(collection)
    • For dictionaries, it sorts based on the keys by default.

Collection-specific Functions

  • Lists:
    • append(): Adds an item to the end of the list.
    • extend(): Adds all elements of a list (or any iterable) to the end of the current list.
    • insert(): Inserts an item at a given position.
    • remove(): Removes the first item from the list that has a specific value.
    • pop(): Removes the item at the given position in the list, and returns it.
  • Sets:
    • add(): Adds an element to a set.

    • remove(): Removes a specific element from a set.

    • discard(): Removes a specific element from a set if it is a member.

    • union(), intersection(), difference(), and symmetric_difference() are set operations that return new sets.

  • Dictionaries:
    • keys(): Returns a view object that displays a list of all the keys.

    • values(): Returns a view object that displays a list of all the values.

    • items(): Returns a view object that displays a list of the dictionary’s key-value tuple pairs.

Using Functions in Iterations

You can combine these functions with loops or comprehensions to perform more complex operations on collections.

  • Example: Filtering a list of numbers to find only the even numbers, then calculating their sum.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
total = sum(even_numbers)
print("Sum of even numbers:", total)