Data Structures
Python Lists, Tuples, & Sets: Part 4
This provides an introduction to three fundamental data structures in Python, and built-in functionality using lists, tuples, & sets.
Ryan McBride
Ryan McBride
alt

Source: fabio from Unsplash

Lists

  • Lists are ordered sequences of items, allowing for duplicates.
  • They are created using square brackets [] with comma-separated values.
    
    my_list = [1, 2, 2, 3, "apple", "banana"]
    print(my_list)  # Output: [1, 2, 2, 3, 'apple', 'banana']
                    
  • You can find the number of items in a list using the len() function.
    
    print(len(my_list))  # Output: 6
                    
  • Individual items are accessed using their index, starting from 0. Negative indexing can be used to access elements from the end of the list.
    
    print(my_list[0])   # Output: 1
    print(my_list[-1])  # Output: banana
                    
  • Slicing allows you to access a range of items using a colon : within the square brackets. The starting index is inclusive, and the ending index is exclusive.
    
    print(my_list[1:4])  # Output: [2, 2, 3]
                    
  • Various methods can modify lists:
    • append() adds an item to the end.
      
      my_list.append("cherry")
      print(my_list)  # Output: [1, 2, 2, 3, 'apple', 'banana', 'cherry']
                              
    • insert() adds an item at a specific index.
      
      my_list.insert(2, "grape")
      print(my_list)  # Output: [1, 2, 'grape', 2, 3, 'apple', 'banana', 'cherry']
                              
    • extend() adds multiple items from another iterable (like another list) to the end.
      
      my_list.extend([4, 5])
      print(my_list)  # Output: [1, 2, 'grape', 2, 3, 'apple', 'banana', 'cherry', 4, 5]
                              
    • remove() removes the first occurrence of a specific value.
      
      my_list.remove(2)
      print(my_list) # Output: [1, 'grape', 2, 3, 'apple', 'banana', 'cherry', 4, 5]
                              
    • pop() removes and returns the item at a given index (or the last item if no index is provided).
      
      popped_item = my_list.pop(1)
      print(popped_item)  # Output: grape
      print(my_list)      # Output: [1, 2, 3, 'apple', 'banana', 'cherry', 4, 5]
                              
    • reverse() reverses the order of the list in place.
      
      my_list.reverse()
      print(my_list) # Output: [5, 4, 'cherry', 'banana', 'apple', 3, 2, 1]
                              
    • sort() sorts the list in place (alphabetically for strings, ascending for numbers). The reverse=True argument sorts in descending order.
      
      # my_list.sort()  # This will cause an error because the list contains both strings and numbers
      num_list = [3, 1, 4, 1, 5, 9, 2, 6]
      num_list.sort()
      print(num_list) # Output: [1, 1, 2, 3, 4, 5, 6, 9]
      num_list.sort(reverse=True)
      print(num_list) # Output: [9, 6, 5, 4, 3, 2, 1, 1]
                              
  • The sorted() function returns a new sorted list without modifying the original.
    
    new_list = sorted(num_list)
    print(new_list) # Output: [1, 1, 2, 3, 4, 5, 6, 9]
    print(num_list) # Output: [9, 6, 5, 4, 3, 2, 1, 1]
                    
  • Built-in functions like min(), max(), and sum() can be used with lists of numbers.
    
    print(min(num_list)) # Output: 1
    print(max(num_list)) # Output: 9
    print(sum(num_list)) # Output: 32
                    
  • The index() method finds the index of the first occurrence of a value.
    
    print(num_list.index(5)) # Output: 4
                    
  • The in operator checks if a value exists in the list.
    
    print(5 in num_list)  # Output: True
    print(10 in num_list) # Output: False
                    
  • You can iterate through a list using a for loop. The enumerate() function provides both the index and the value during iteration.
    
    for item in my_list:
        print(item)
    
    for index, item in enumerate(my_list):
        print(f"Index: {index}, Item: {item}")
                    
  • The join() string method can concatenate list items into a string with a specified separator.
    
    string_list = ["hello", "world", "python"]
    joined_string = " ".join(string_list)
    print(joined_string) # Output: hello world python
                    
  • The split() string method can split a string into a list based on a delimiter.
    
    my_string = "apple,banana,cherry"
    split_list = my_string.split(",")
    print(split_list) # Output: ['apple', 'banana', 'cherry']
                    

Tuples

  • Tuples are similar to lists but are immutable, meaning their elements cannot be changed after creation.
  • They are defined using parentheses ().
  • Due to their immutability, they have fewer methods than lists (no append, remove, insert, etc.).
  • They are useful for representing fixed collections of items.
    
    my_tuple = (1, 2, 3, "apple", "banana")
    print(my_tuple)        # Output: (1, 2, 3, 'apple', 'banana')
    print(my_tuple[0])     # Output: 1
    print(my_tuple[1:3])   # Output: (2, 3)
    
    # my_tuple[0] = 5 # This will cause an error
                    

Sets

  • Sets are unordered collections of unique elements, meaning they do not allow duplicates.
  • They are defined using curly braces {}.
  • The order of elements in a set is not guaranteed.
  • Sets are efficient for membership testing using the in operator.
  • They provide methods for set operations:
    • intersection(): returns common elements between sets.
    • difference(): returns elements present in one set but not the other.
    • union(): returns all unique elements from both sets.
      
      my_set = {1, 2, 2, 3, "apple", "banana"}
      print(my_set) # Output: {1, 2, 3, 'apple', 'banana'} (order may vary)
      
      print(2 in my_set)  # Output: True
      
      set1 = {1, 2, 3, 4}
      set2 = {3, 4, 5, 6}
      
      print(set1.intersection(set2)) # Output: {3, 4}
      print(set1.difference(set2))   # Output: {1, 2}
      print(set1.union(set2))        # Output: {1, 2, 3, 4, 5, 6}
                              

Creating Empty Collections

  • Empty lists can be created with [] or list().
  • Empty tuples can be created with () or tuple().
  • Empty sets must be created using set() (not {} which creates an empty dictionary).
    
    empty_list = []
    empty_list2 = list()
    
    empty_tuple = ()
    empty_tuple2 = tuple()
    
    empty_set = set()
    # empty_set = {} # This creates an empty dictionary