Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

≀Paulo Portela
≀Paulo Portela

Posted on

Working with Sets and Frozen Sets in Python

In this post, we'll explore sets and frozen sets in Python, using an astronomy theme to provide code examples. Sets are unordered collections of unique elements, while frozen sets are immutable versions of sets. Let's get started.

First, let's create a set of planets in our solar system:

planets={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"}print(planets)# Output: {'Venus', 'Jupiter', 'Earth', 'Mars', 'Saturn', 'Neptune', 'Uranus', 'Mercury'}
Enter fullscreen modeExit fullscreen mode

In this example, we create a set calledplanets containing the names of the eight planets in our solar system. Since sets are unordered, the elements are not displayed in any particular order.

We can add elements to a set using the add method:

planets.add("Pluto")print(planets)# Output: {'Venus', 'Jupiter', 'Earth', 'Mars', 'Saturn', 'Neptune', 'Uranus', 'Mercury', 'Pluto'}
Enter fullscreen modeExit fullscreen mode

In this example, we add the dwarf planet Pluto to our set of planets using theadd method.

We can remove elements from a set using theremove method or thediscard method. Theremove method raises an error if the element is not found, while thediscard method does not:

planets.remove("Pluto")print(planets)# Output: {'Venus', 'Jupiter', 'Earth', 'Mars', 'Saturn', 'Neptune', 'Uranus', 'Mercury'}
Enter fullscreen modeExit fullscreen mode
planets.discard("Pluto")print(planets)# Output: {'Venus', 'Jupiter', 'Earth', 'Mars', 'Saturn', 'Neptune', 'Uranus', 'Mercury'}
Enter fullscreen modeExit fullscreen mode

In this example, we remove Pluto from our set of planets using theremove method. Since Pluto is no longer in the set, calling thediscard method with "Pluto" as an argument has no effect.

We can also remove and return an arbitrary element from a set using thepop method:

planet=planets.pop()print(planet)# Output: Venus
Enter fullscreen modeExit fullscreen mode

In this example, we remove and return an arbitrary element from our set of planets using thepop method. Since sets are unordered, the element returned by thepop method is not predictable.

We can clear all elements from a set using the clear method:

planets.clear()print(planets)# Output: set()
Enter fullscreen modeExit fullscreen mode

In this example, we remove all elements from our set of planets using theclear method.

We can perform set operations such as union, intersection, and difference using theunion,intersection, anddifference methods, respectively:

planets={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"}gas_giants={"Jupiter","Saturn","Uranus","Neptune"}inner_planets=planets.difference(gas_giants)print(inner_planets)# Output: {'Venus', 'Earth', 'Mars', 'Mercury'}
Enter fullscreen modeExit fullscreen mode
outer_planets=planets.intersection(gas_giants)print(outer_planets)# Output: {'Jupiter', 'Saturn', 'Neptune', 'Uranus'}
Enter fullscreen modeExit fullscreen mode

In this example, we create a set of gas giants and use thedifference andintersection methods to find the inner and outer planets, respectively.

We can also check if a set is a subset or superset of another set using theissubset andissuperset methods, respectively:

print(gas_giants.issubset(planets))# Output: True
Enter fullscreen modeExit fullscreen mode
print(planets.issuperset(gas_giants))# Output: True
Enter fullscreen modeExit fullscreen mode

In this example, we use theissubset andissuperset methods to check if the set of gas giants is a subset of the set of planets, and if the set of planets is a superset of the set of gas giants, respectively.

We can also check if two sets are disjoint (have no elements in common) using theisdisjoint method:

rocky_planets={"Mercury","Venus","Earth","Mars"}print(gas_giants.isdisjoint(rocky_planets))# Output: True
Enter fullscreen modeExit fullscreen mode

In this example, we create a set of rocky planets and use theisdisjoint method to check if the set of gas giants and the set of rocky planets have no elements in common.

We can also create a shallow copy of a set using thecopy method:

planets_copy=planets.copy()print(planets_copy)# Output: {'Venus', 'Jupiter', 'Earth', 'Mars', 'Saturn', 'Neptune', 'Uranus', 'Mercury'}
Enter fullscreen modeExit fullscreen mode

In this example, we create a shallow copy of our set of planets using thecopy method.

In addition to sets, Python also has a built-infrozenset type, which is an immutable version of a set. This means that, once created, a frozenset cannot be modified. We can create a frozenset using thefrozenset function:

frozen_gas_giants=frozenset(gas_giants)print(frozen_gas_giants)# Output: frozenset({'Jupiter', 'Saturn', 'Neptune', 'Uranus'})
Enter fullscreen modeExit fullscreen mode

In this example, we create afrozenset of gas giants using the frozenset function. Since frozensets are immutable, we cannot add or remove elements from them.

That concludes our introduction to sets and frozen sets in Python. We've covered the basics of creating and accessing sets and frozen sets, as well as some of their useful methods and attributes. Sets and frozen sets are powerful tools for working with collections of unique elements, and can be a useful addition to your Python toolkit.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Portugal
  • Education
    ISEP
  • Work
    Senior Software Developer @ adidas
  • Joined

More from≀Paulo Portela

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp