DEV Community

Romulo Gatto
Romulo Gatto

Posted on

Advanced Data Structures: Sets, Tuples, and Comprehensions

Advanced Data Structures: Sets, Tuples, and Comprehensions

In the world of programming, data manipulation and organization are of paramount importance. Python provides a variety of data structures to fulfill this purpose. Three such advanced data structures are sets, tuples, and comprehensions. This guide will explore these powerful tools and learn how to work with them in your Python code efficiently.

Sets

Sets in Python are unordered collections of unique items enclosed within curly braces {}. They provide useful operations like intersection, union, difference, and membership testing.

Creating a Set

To create a set in Python, simply enclose the items within curly braces or use the set() function:

my_set = {1, 2, 3}      # using curly braces
my_other_set = set([4, 5])   # using set() function
Enter fullscreen mode Exit fullscreen mode

Modifying a Set

Sets are mutable; therefore new elements can be added or existing elements can be removed easily:

my_set.add(4)              # adds element '4' to my_set

my_other_set.remove(5)     # removes element '5' from my_other_set if it exists,
                           # otherwise raises KeyError

my_other_set.discard(6)    # removes element '6' from my_other_set if it exists,
                           # otherwise does nothing (no error)
Enter fullscreen mode Exit fullscreen mode

Operations on Sets

Python offers several built-in methods for manipulating sets efficiently:

  • Union (|):
        united = set1 | set2    # returns a new set containing all distinct elements from both sets 
Enter fullscreen mode Exit fullscreen mode
  • Intersection (&):
       common_elements = set1 & set2    # returns a new set containing only common elements between both sets 
Enter fullscreen mode Exit fullscreen mode
  • Difference (-):
       set_diff = set1 - set2     # returns a new set containing elements that are in `set1` but not in `set2`
Enter fullscreen mode Exit fullscreen mode
  • Symmetric Difference (^):
       sym_diff = set1 ^ set2     # returns a new set containing elements that are unique to each of the sets 
Enter fullscreen mode Exit fullscreen mode

Useful Set Operations

The following operations help determine relationships between sets:

  • Subset (<=) and Superset (>=)

        is_subset = subset <= superset    # checks if every element of subset exists in the superset (returns boolean)

        is_superset = superset >= subset  # checks if every element of superset exists in the subset (returns boolean)

Enter fullscreen mode Exit fullscreen mode
  • Membership (in)

          is_member = 4 in my_set    # checks if an element exists within the given set (returns boolean)

Enter fullscreen mode Exit fullscreen mode

Tuples

Tuples are similar to lists but cannot be changed once created. They are immutable and enclosed within parentheses ().

Creating a Tuple

Creating a tuple is as simple as enclosing your items within parentheses or using the built-in tuple() function:

my_tuple = (1, 'a', True)                  # using parentheses

my_other_tuple= tuple([3.14, 'b', False])  # using tuple() function

Enter fullscreen mode Exit fullscreen mode

Accessing Elements

To access individual elements of a tuple, use indexing just like you would with lists:

first_item = my_tuple[0]            // outputs: 1

second_item = my_other_tuple[1]     // outputs: 'b'


length_of_tuple= len(my_other_tuple)     // outputs: 3

Enter fullscreen mode Exit fullscreen mode

Comprehensions

Comprehensions provide an elegant way to create new sequences, such as lists, sets, or dictionaries.

List Comprehensions

List comprehensions allow you to generate a list by applying an expression to each element of an existing sequence:

my_list = [x for x in range(10)]        # generates a list containing numbers from 0 to 9

squared_numbers = [x**2 for x in my_list]     # generates a list containing squared numbers

Enter fullscreen mode Exit fullscreen mode

Set and Dictionary Comprehensions

Set and dictionary comprehensions follow similar patterns. The only distinction is the use of curly braces {} instead of square brackets []:

my_set = {x**3 for x in range(5)}          # generates a set containing the cube of each number from 0 to 4

my_dict = {x: x*2 for x in range(5)}      # generates a dictionary with keys as numbers and values as their doubles
Enter fullscreen mode Exit fullscreen mode

Comprehensions can also include conditions that filter elements based on certain criteria:

even_squares = [x**2 for x in my_list if x % 2 == 0]    # creates a filtered list consisting of squared even numbers

divisible_by_three_and_five= {x for x in range(30) if (x % 3 == 0) and (x % 5 ==0)} 
# creates a set of numbers divisible by both three and five within the given range
Enter fullscreen mode Exit fullscreen mode

With this guide, you now have a strong foundation in working with sets, tuples, and comprehensions. Start implementing these powerful data structures into your Python projects today!

Top comments (0)