Lists and Tuples

Jul 11, 2024

Lecture on Lists and Tuples

Introduction to Lists

  • Definition: A versatile and mutable data structure used to store a collection of items.
  • Creation:
    my_list = [1, 2, 3, 'apple']
    
  • Characteristics:
    • Managed using square brackets []
    • Can contain different data types: integers, strings, floats, etc.
    • Duplicate entries allowed

Manipulating Lists

Accessing Elements

  • Use indexing (0-based and negative indexing)
  • Example:
    my_list[0]  # First element
    my_list[-1] # Last element
    

Slicing

  • Extract portions of a list
  • Syntax: my_list[start:stop]

Modifying Elements

  • Change elements based on index, insert or remove items
  • Example:
    my_list[1] = 'pear'  # Modify second element
    

Methods

  • append(): Add elements to the end
  • insert(): Add elements at a specific index
  • remove(): Remove a specific element
  • pop(): Remove the last item or item at a specific index
  • count(): Returns the count of the specified item in the list
  • sort(): Sorts the list, can be customized with key and reverse parameters
  • extend(): Extends the list by appending elements from iterable
  • index(): Returns the index of the specified value
  • copy(): Returns a shallow copy of the list
  • clear(): Removes all the elements from the list

List Comprehensions

  • Provides a concise way to create lists
  • Example:
    squares = [x*x for x in range(10)]
    

Introduction to Tuples

  • Definition: Similar to lists but immutable
  • Creation:
    my_tuple = (1, 2, 3, 'apple')
    
  • Characteristics:
    • Managed using parentheses ()
    • Once created, the tuple cannot be changed
    • Can contain different data types
    • Duplicate entries allowed

Accessing Tuple Elements

  • Similar to lists using indexing and slicing
  • Example:
    my_tuple[0]  # First element
    my_tuple[-1] # Last element
    

Introduction to Sets

  • Definition: Unordered collections of unique elements
  • Creation:
    my_set = {1, 2, 3, 'apple'}
    
    or using the set function:
    my_set = set([1, 2, 3, 'apple'])
    
  • Characteristics:
    • Duplicate entries are removed automatically
    • Can contain different data types
    • Managed using curly braces {}
    • Unordered collections

Set Operations

  • add(): Add a single element
  • update(): Add multiple items
  • remove()/discard(): Remove specific item, discard() doesn't raise an error if item doesn't exist
  • pop(): Remove and return an arbitrary element
  • clear(): Remove all elements
  • union(): Return a set containing all elements from both sets
  • intersection(): Return a set containing only elements that are in both sets
  • difference(): Return a set containing all the elements of invoking set but not of the other
  • symmetric_difference(): Return a set containing all elements from both sets, but not in both
  • issubset(): Return True if set is a subset of another set
  • issuperset(): Return True if set is a superset of another set
  • copy(): Return a shallow copy of the set
  • frozenset(): Immutable version of a set

Introduction to Dictionaries

  • Definition: Collections of key-value pairs
  • Creation:
    my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
    
  • Characteristics:
    • Managed using curly braces {}
    • Keys must be unique and immutable
    • Values can be of any data type
    • Supports addition, updating, and deletion of items

Accessing and Manipulating Dictionaries

  • Accessing Values:
    my_dict['name']  # John
    
  • Updating Values:
    my_dict['age'] = 31
    
  • Adding New Key-Value Pairs:
    my_dict['email'] = 'john@example.com'
    
  • Removing Key-Value Pairs:
    my_dict.pop('age')  # Removes 'age' key
    
  • Methods:
    • keys(): Returns a list of all the keys in the dictionary
    • values(): Returns a list of all the values in the dictionary
    • items(): Returns a list of tuples for each key-value pair
    • get(): Returns the value for a key, returns None if key does not exist
    • update(): Updates the dictionary with elements from another dictionary or iterable of key-value pairs
    • clear(): Removes all the elements
    • copy(): Returns a shallow copy of the dictionary

Looping Through Dictionaries

  • Loop through keys:
    for key in my_dict:
        print(key, my_dict[key])
    
  • Loop through values:
    for value in my_dict.values():
        print(value)
    
  • Loop through key-value pairs:
    for key, value in my_dict.items():
        print(key, value)
    

Dictionary Comprehensions

  • Definition: A way to create dictionaries using a single line of code
  • Example:
    {x: x*x for x in range(5)}  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
    

Practical Problems

Problem 1: Sum of List Elements

  • Task: Find the sum of all elements in a given list of numbers
  • Approach: Loop through elements and accumulate sum
  • Example:
    def sum_list(lst):
        total = 0
        for num in lst:
            total += num
        return total
    

Problem 2: Maximum and Minimum Elements in List

  • Task: Find the maximum and minimum elements in a list
  • Approach: Use built-in functions max() and min()
  • Example:
    my_list = [3, 1, 4, 1, 5, 9, 2]
    max_val = max(my_list)
    min_val = min(my_list)
    print(f"Max: {max_val}, Min: {min_val}")
    

Problem 3: Unique Elements in List

  • Task: Remove duplicate elements from a list
  • Approach: Use set to remove duplicates
  • Example:
    def unique_elements(lst):
        return list(set(lst))
    

Problem 4: Count Occurrences of Element in List

  • Task: Count the number of occurrences of a specific element in a list
  • Approach: Use the count method
  • Example:
    def count_occurrences(lst, val):
        return lst.count(val)
    

Problem 5: Set Operations

  • Task: Given two sets, find their intersection and union
  • Approach: Use set methods
  • Example:
    set1 = {1, 2, 3, 4}
    set2 = {3, 4, 5, 6}
    union_set = set1.union(set2)
    intersection_set = set1.intersection(set2)
    

Problem 6: Dictionary Operations

  • Task: Create a dictionary, access values, update values, and iterate through key-value pairs
  • Approach: Use dictionary methods
  • Example:
    my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
    my_dict['age'] = 31  # Update value
    for key, value in my_dict.items():
        print(f"{key}: {value}")
    

Summary

  • Lists and tuples offer a straightforward way to manage collections of items, lists being mutable and tuples immutable.
  • Sets offer a way to handle unique item collections with support for standard mathematical set operations.
  • Dictionaries enable the pairing of keys and values, facilitating complex data management.
  • Practical problem-solving with these data structures involves correctly leveraging their operations and understanding the appropriate contexts to use them.