Working with Collections in Python

Overview

This lesson focuses on how to work with the various collection data types in Python, including lists, tuples, sets, and dictionaries. You’ll learn how to create, access, manipulate, and iterate through these collections to effectively manage and use data in your Python programs.

Introduction

Collections in Python provide a way to store multiple items in a single variable. Python offers several types of collections, each with its unique features and use cases.

Lists

  • Creation: Use square brackets [] to create a list. Example: fruits = ['apple', 'banana', 'cherry']
  • Accessing Elements: Use indexing and slicing. Example: fruits[0] returns ‘apple’.
  • Manipulation: Append, insert, remove, or sort items. Example: fruits.append('orange')

Read more about Lists in Python.

Tuples

  • Creation: Use parentheses () to create a tuple. Example: coordinates = (10.0, 20.0)
  • Accessing Elements: Use indexing. Example: coordinates[0] returns 10.0.
  • Immutability: Tuples cannot be changed after creation.

Read more about Tuples in Python.

Sets

  • Creation: Use curly braces {} or the set() function. Example: colors = {'red', 'green', 'blue'}
  • Unique Elements: Sets automatically remove duplicates.
  • Operations: Perform union, intersection, difference, and symmetric difference.

Read more about Sets in Python.

Dictionaries

  • Creation: Use curly braces {} with key-value pairs. Example: person = {'name': 'John', 'age': 30}
  • Accessing Elements: Use keys. Example: person['name'] returns ‘John’.
  • Manipulation: Add, remove, or update key-value pairs.

Read more about Dictionaries in Python.

Iterating Through Collections

  • For Loops: Iterate over each item in a collection. Example: for fruit in fruits: print(fruit)

  • List Comprehension: Create new lists by applying an expression to each item in an existing list. Example: [x.upper() for x in fruits]

Read more about Iterating Through Collections.

Conditional Statements in Collections

  • Use if statements to check for the presence of an item or to filter items. Example: [x for x in fruits if 'a' in x]

Read more about Conditional Statements in Python.

Functions for Collections

  • Python provides built-in functions like len(), min(), max(), and sum() for working with collections.

  • Sorting: Use the sorted() function for any iterable and the .sort() method for lists.

Read more about Functions for Collections.

Advanced Techniques

  • Nested Collections: Store collections within collections. Example: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

  • Unpacking: Assign elements of a collection to multiple variables. Example: x, y, z = coordinates

Conclusion

Working with collections is essential for handling multiple data items in Python. By mastering lists, tuples, sets, and dictionaries, you can efficiently store, access, manipulate, and iterate through your data.

Additional Resources