Understanding Python Lists and Operations

Aug 25, 2024

Python Lists Lecture Notes

Introduction

  • Host: Ivan Jetty
  • Topic: Working with lists in Python

Overview of Lists

  • Lists in Python are similar to arrays in C/C++/Java.
  • They can contain various data types (numbers, strings, etc.).

Creating a List

  • Syntax: nums = [25, 12, 636, 95, 14]
  • Lists are defined using square brackets.

Accessing List Elements

  • Indexing:
    • First element: nums[0] returns 25
    • Last element: nums[-1] returns 14
    • Subrange (e.g., from third element to end): nums[2:] returns [636, 95, 14]
    • Negative indexing works as well (e.g., nums[-5] returns 25).

List of Different Data Types

  • Example list with mixed types: values = [9.5, "My Name", 25]
  • Lists can contain different types of data (unlike arrays in languages such as C, C++ where the type is fixed).

Nested Lists

  • Example of a nested list: mil = [nums, names]
  • mil contains both numbers and strings.

List Methods and Mutability

  • Lists are mutable, which means you can change their contents.
  • Common methods:
    • append(value): Adds an element at the end.
    • insert(index, value): Inserts an element at a specific index.
    • remove(value): Removes the first occurrence of a value.
    • pop(index): Removes and returns an element at a specific index (or last element if no index is provided).
    • clear(): Clears all elements from the list.
    • extend([values]): Adds multiple elements to the end of the list.

Examples of List Operations

  • Appending a value: nums.append(45)
  • Inserting a value: nums.insert(2, 2077)
  • Removing a value: nums.remove(14)
  • Using pop without an index removes the last added element.

Deleting Multiple Values

  • del nums[2:]: Deletes all elements from index 2 to the end.

Built-in Functions for Lists

  • min(nums): Returns the minimum value in the list.
  • max(nums): Returns the maximum value in the list.
  • sum(nums): Returns the sum of all elements.
  • sort(): Sorts the elements of the list in ascending order.

Conclusion

  • Lists in Python are versatile:
    • Can hold different data types.
    • Can be modified with various methods.
    • Support indexing and slicing.
  • Encouraged to experiment with list methods and refer to Python documentation for more information.