Table of Content

Operators



In Python, operators are symbols used to perform operations on variables or values. They include arithmetic operators (+, -, *, /, %), comparison operators (==, !=, <, >, <=, >=), assignment operators (=, +=, -=, *=, /=), logical operators (and, or, not), bitwise operators (&, |, ^, ~, <<, >>), and more.

These operators allow you to manipulate data, perform calculations, compare values, and control program flow. Here are some examples of operators in Python:


Arithmetic operators::

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulus: %

python
# Creating a set
my_set = {1, 2, 3}
another_set = set([4, 5, 6])

print("my_set =", my_set)
print("another_set =", another_set)

Output:

python
my_set = {1, 2, 3}
another_set = {4, 5, 6}

Adding and Removing Elements:

Elements can be added to a set using the add() method, and removed using the remove() or discard() methods.

python
my_set = {1, 2, 3}

my_set.add(4)
my_set.remove(3)

print("Updated my_set after adding 4 and removing 3:", my_set)

Output:

python
Updated my_set after adding 4 and removing 3: {1, 2, 4}

Operations on Sets:

Sets support various operations, including union ( | ), intersection (&), difference (-), and symmetric difference (^).

python
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union
print(set1 | set2)  # Output: {1, 2, 3, 4, 5}

# Intersection
print(set1 & set2)  # Output: {3}

# Difference
print(set1 - set2)  # Output: {1, 2}

Output:

python
{1, 2, 3, 4, 5}
{3}
{1, 2}

Membership:

You can check if an element is present in a set using the in operator.

python
print(3 in my_set)

Output:

python
True

Length of Sets:

The len() function returns the number of elements in a set.

python
print(len(my_set))

Output:

python
3

Iteration:

You can iterate over the elements of a set using a for loop.

python
for element in my_set:
      print(element)

Output:

python
1
2
3

Set Comprehensions:

Similar to list comprehensions, you can use set comprehensions to create sets based on existing iterables.

python
squares = {x**2 for x in range(10)}

The output for the given expression squares = {x**2 for x in range(10)} would be a set containing the squares of numbers from 0 to 9.

Output:

python
{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

Explanation:

  • The expression {x**2 for x in range(10)} is a set comprehension that generates a set by iterating over the numbers from 0 to 9 (inclusive) using range(10).
  • For each number x, it calculates the square x**2.
  • As a result, it produces a set containing the squares of numbers from 0 to 9.