Python Reference

Quick Reference

The Python set union() method returns a set that contains all items from the original set, and all items from the specified set(s).

  • Any number of sets/iterables can be specified, separated by commas
  • It does not have to be a set, it can be any iterable object
  • If an item is present in more than one set, the result will contain only one appearance of the item

Example 1:

x = {"Ferrari", "Maserati", "Alfa Romeo"}
y = {"Lamborgini", "Ferrari", "Astin Martin"}

z = x.union(y) 
print(z)

Example 2:

x = {"Ferrari", "Maserati", "Alfa Romeo"}
y = {"Lamborgini", "Ferrari", "Astin Martin"}

z = x | y 
print(z)

Note

In example 2, using the pipe (|) separator, sets can only be joined with other sets, NOT any other iterables as can be done in the first example.

Output

{'Astin Martin', 'Alfa Romeo', 'Lamborgini', 'Maserati', 'Ferrari'}

Syntax

set.union(set1, set2, ...)

// or

set | set1 | set2 | ...

Parameters

ParameterDescription
set1The iterable to unify with (required)
set2The other iterable to unify with; you can compare as many iterables as you like by separating each iterable with a comma (or if using the shortcut version a | pipe operator)

Python Notes:

  • The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
  • Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
  • Python string methods return new values, and DO NOT change the original string
  • Python tuples are unchangeable after created (their items CANNOT be changed or re-ordered at a later point)
  • Python sets are unordered (may appear in random orders when called), unchangeable (the value of individual items cannot be changed after creation), and unindexed (items cannot be referred to by index or key)

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.