Python Lists Lecture

Jul 30, 2024

Python Lists Lecture Notes

Introduction to Lists

  • Python lists are similar to arrays in languages like C, C++, and Java.
  • Can hold different types of data (numbers, strings, etc.) in a single list.

Creating Lists

  • To create a list, use square brackets [ ] and separate values with commas.
    nums = [25, 12, 636, 95, 14]
    
  • Can print the entire list with print(nums).

Accessing List Elements

  • Access elements using index values (0-based indexing).
  • Example: nums[0] returns the first element (25).
  • Can also access the last element using negative indexing: nums[-1] returns 14.

Slicing Lists

  • Slicing allows retrieval of a range of elements.
    • Example: nums[2:] retrieves third element to the end.
  • Similar to string slicing used previously.
  • Can use negative indexing for slicing as well.

Lists with Different Data Types

  • Lists can contain mixed data types:
    values = [9.5, 'name', 25]
    

Nested Lists

  • Lists can contain other lists (nested lists).
    mil = [nums, names]
    

List Methods and Mutability

  • Lists are mutable (can be changed after creation).
  • Common list methods:
    • append(value): Adds a value at the end.
    • insert(index, value): Inserts a value at a specific index.
    • remove(value): Removes the first occurrence of the specified value.
    • pop(index): Removes and returns the item at the specified index (or last item if no index is provided).
    • clear(): Removes all items from the list.
    • extend([other_values]): Adds multiple elements to the end of the list.

Examples of List Operations

  • Appending values:
    nums.append(45)
    
  • Inserting values:
    nums.insert(2, 2077)
    
  • Removing values:
    nums.remove(14)
    
  • Using pop:
    nums.pop(1)
    
  • Using del to remove a range of elements:
    del nums[2:]  # Deletes from index 2 to end
    

Using Python Built-in Functions

  • List has built-in functions to find min, max, sum:
    • min(nums) - returns minimum value.
    • max(nums) - returns maximum value.
    • sum(nums) - returns total sum.
    • sort() - sorts the list in ascending order.

Conclusion

  • Lists offer a versatile way to store collections of data in Python.
  • Ability to hold multiple data types, perform operations, and modify content dynamically.
  • Encourage viewers to explore the documentation for more methods and features.

Call to Action

  • Encourage viewers to engage with the content via comments and thumbs up if they found it helpful.