Understanding Python Lists, Tuples, and Sets

Aug 14, 2024

Python Data Structures: Lists, Tuples, and Sets

Overview

  • Lists: Ordered collections of values.
  • Tuples: Immutable ordered collections.
  • Sets: Unordered collections of unique values.

Lists

Creating Lists

  • Use square brackets [] to define a list.
  • Example:
    courses = ["History", "Math", "Physics", "Comp Sci"]
    

Common Operations

  • Length: Use len() to find the number of items in a list.
    len(courses)  # Returns 4
    
  • Accessing Items: Use zero-based indexing.
    courses[0]  # Returns "History"
    courses[3]  # Returns "Comp Sci"
    
  • Negative Indexing: Access items from the end of the list.
    courses[-1]  # Returns "Comp Sci"
    

Slicing Lists

  • Access a range of values.
    courses[0:2]  # Returns ["History", "Math"]
    courses[2:]   # Returns ["Physics", "Comp Sci"]
    

Modifying Lists

  • Append: Add an item to the end of the list.
    courses.append("Art")
    
  • Insert: Add an item at a specific index.
    courses.insert(0, "Art")  # Inserts "Art" at index 0
    
  • Extend: Add multiple items from another list.
    courses.extend(["Art", "Education"])
    
  • Remove: Remove an item by value.
    courses.remove("Math")
    
  • Pop: Remove an item by index (default is the last item).
    popped_course = courses.pop()
    

Sorting and Reversing Lists

  • Reverse: Reverse the order of items.
    courses.reverse()
    
  • Sort: Sort items in ascending order.
    courses.sort()
    
  • Sorted Function: Returns a sorted list without modifying the original.
    sorted_courses = sorted(courses)
    

Built-in Functions

  • Min/Max/Sum: Get minimum, maximum, or sum of a list.
    min(numbers), max(numbers), sum(numbers)
    

Membership Testing

  • Check if an item exists in a list.
    "Art" in courses
    

Looping Through Lists

  • Use for loops to iterate through a list.
    for item in courses:
        print(item)
    
  • Enumerate: Get indexes along with values.
    for index, course in enumerate(courses):
        print(index, course)
    

Joining and Splitting Lists

  • Join list items into a string.
    course_string = ', '.join(courses)
    
  • Split a string back into a list.
    new_list = course_string.split(', ')
    

Tuples

  • Definition: Similar to lists but immutable.
  • Creation: Use parentheses () instead of square brackets.
    courses_tuple = ("History", "Math", "Physics")
    
  • Modification: Cannot change values, append, or remove items.
  • Use Case: For collections of values that should not change.

Sets

  • Definition: Unordered collection of unique items.
  • Creation: Use curly braces {} or set() function.
    courses_set = {"History", "Math", "Physics"}
    
  • Membership Testing: Check if an item exists, faster than lists.
    "Math" in courses_set
    
  • Operations:
    • Union: Combine two sets.
    • Intersection: Common items in both sets.
    • Difference: Items in one set but not the other.

Creating Empty Data Structures

  • Empty List: [] or list().
  • Empty Tuple: () or tuple().
  • Empty Set: set() (not {} as it creates an empty dictionary).

Conclusion

  • Understanding lists, tuples, and sets is crucial for managing data in Python. Questions can be left in the comments.