Python Collections

Harsh Mishra - Jun 27 - - Dev Community

Lists in Python

Lists are one of the most versatile and widely used data types in Python. They allow you to store collections of items in a single variable. Here's everything you need to know about lists in Python.

Creating Lists

Lists are created by placing a comma-separated sequence of items within square brackets [].

# Creating a list of integers
numbers = [1, 2, 3, 4, 5]

# Creating a list of strings
fruits = ["apple", "banana", "cherry"]

# Creating a mixed data type list
mixed = [1, "hello", 3.14, True]

# Creating a nested list
nested = [[1, 2], [3, 4], [5, 6]]
Enter fullscreen mode Exit fullscreen mode

Accessing Elements

You can access elements of a list by using indexing. Indexing starts at 0.

numbers = [1, 2, 3, 4, 5]
print(numbers[0])  # Output: 1
print(numbers[4])  # Output: 5
Enter fullscreen mode Exit fullscreen mode

Negative indexing allows you to access elements from the end of the list.

print(numbers[-1])  # Output: 5
print(numbers[-2])  # Output: 4
Enter fullscreen mode Exit fullscreen mode

Slicing Lists

You can retrieve a part of a list by using slicing. The syntax for slicing is list[start:stop:step].

# Creating a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slicing from index 2 to 5
print(numbers[2:6])  # Output: [3, 4, 5, 6]

# Slicing with step
print(numbers[::2])  # Output: [1, 3, 5, 7, 9]

# Slicing with negative step (reversing the list)
print(numbers[::-1])  # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

Modifying Lists

Lists are mutable, meaning you can change their content.

numbers = [1, 2, 3, 4, 5]

# Changing an element
numbers[0] = 10
print(numbers)  # Output: [10, 2, 3, 4, 5]

# Changing a range of elements
numbers[1:3] = [20, 30]
print(numbers)  # Output: [10, 20, 30, 4, 5]
Enter fullscreen mode Exit fullscreen mode

List Concatenation

You can concatenate two or more lists using the + operator.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined)  # Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

List Comprehensions

List comprehensions provide a concise way to create lists. It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses.

# Creating a list of squares
squares = [x**2 for x in range(10)]
print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Filtering with list comprehensions
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # Output: [0, 4, 16, 36, 64]
Enter fullscreen mode Exit fullscreen mode

Iterating Over Lists

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

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# cherry
Enter fullscreen mode Exit fullscreen mode

Checking Membership

You can check if an item exists in a list using the in keyword.

fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)  # Output: True
print("grape" in fruits)  # Output: False
Enter fullscreen mode Exit fullscreen mode

List Length

You can get the number of items in a list using the len() function.

fruits = ["apple", "banana", "cherry"]
print(len(fruits))  # Output: 3
Enter fullscreen mode Exit fullscreen mode

Copying Lists

Copying a list can be done in several ways. It's important to note that simply using the assignment operator (=) does not create a copy but rather a reference to the same list.

# Using slicing
original = [1, 2, 3]
copy = original[:]
print(copy)  # Output: [1, 2, 3]

# Using the list() function
copy = list(original)
print(copy)  # Output: [1, 2, 3]

# Using the copy() method (Python 3.3+)
copy = original.copy()
print(copy)  # Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Nesting Lists

Lists can contain other lists, allowing you to create complex data structures like matrices.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Accessing nested list elements
print(matrix[0][1])  # Output: 2
Enter fullscreen mode Exit fullscreen mode

Unpacking Lists

You can unpack lists into variables directly.

numbers = [1, 2, 3]
a, b, c = numbers
print(a, b, c)  # Output: 1 2 3

# Extended unpacking (Python 3.0+)
numbers = [1, 2, 3, 4, 5]
a, *b, c = numbers
print(a, b, c)  # Output: 1 [2, 3, 4] 5
Enter fullscreen mode Exit fullscreen mode

Lists Methods in Python

Adding Elements

append

  • Appends an item to the end of the list.
  • Syntax: list.append(item)
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)  # Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

extend

  • Extends the list by appending all the items from the iterable.
  • Syntax: list.extend(iterable)
numbers = [1, 2, 3]
numbers.extend([4, 5])
print(numbers)  # Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

insert

  • Inserts an item at a given position.
  • Syntax: list.insert(index, item)
numbers = [1, 2, 3]
numbers.insert(1, 1.5)
print(numbers)  # Output: [1, 1.5, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Removing Elements

remove

  • Removes the first item from the list whose value is equal to the specified value.
  • Syntax: list.remove(item)
numbers = [1, 2, 3, 2]
numbers.remove(2)
print(numbers)  # Output: [1, 3, 2]
Enter fullscreen mode Exit fullscreen mode

pop

  • Removes and returns the item at the given position. If no index is specified, it removes and returns the last item.
  • Syntax: list.pop([index])
numbers = [1, 2, 3]
last_item = numbers.pop()
print(last_item)  # Output: 3
print(numbers)   # Output: [1, 2]

first_item = numbers.pop(0)
print(first_item)  # Output: 1
print(numbers)     # Output: [2]
Enter fullscreen mode Exit fullscreen mode

clear

  • Removes all items from the list.
  • Syntax: list.clear()
numbers = [1, 2, 3]
numbers.clear()
print(numbers)  # Output: []
Enter fullscreen mode Exit fullscreen mode

Information About the List

count

  • Returns the number of times the specified item appears in the list.
  • Syntax: list.count(item)
numbers = [1, 2, 2, 3]
count_twos = numbers.count(2)
print(count_twos)  # Output: 2
Enter fullscreen mode Exit fullscreen mode

index

  • Returns the index of the first item whose value is equal to the specified value.
  • Syntax: list.index(item, [start, [end]])
numbers = [1, 2, 3, 2]
index_of_two = numbers.index(2)
print(index_of_two)  # Output: 1

index_of_two_from_2 = numbers.index(2, 2)
print(index_of_two_from_2)  # Output: 3
Enter fullscreen mode Exit fullscreen mode

Copying and Reversing

copy

  • Returns a shallow copy of the list.
  • Syntax: list.copy()
numbers = [1, 2, 3]
numbers_copy = numbers.copy()
print(numbers_copy)  # Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

reverse

  • Reverses the elements of the list in place.
  • Syntax: list.reverse()
numbers = [1, 2, 3]
numbers.reverse()
print(numbers)  # Output: [3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

Sorting

sort

  • Sorts the items of the list in place.
  • Syntax: list.sort(key=None, reverse=False)
numbers = [3, 1, 2]
numbers.sort()
print(numbers)  # Output: [1, 2, 3]

numbers.sort(reverse=True)
print(numbers)  # Output: [3, 2, 1]

# Sorting with a key
numbers = ["apple", "banana", "cherry"]
numbers.sort(key=len)
print(numbers)  # Output: ['apple', 'cherry', 'banana']
Enter fullscreen mode Exit fullscreen mode

Tuples in Python

Tuples are a type of collection in Python that allows you to group multiple items together. Unlike lists, tuples are immutable, meaning that once they are created, their contents cannot be changed. This immutability makes tuples useful for ensuring data integrity and preventing accidental modification.

Creating Tuples

You can create a tuple by placing a comma-separated sequence of values inside parentheses.

# Creating a tuple
my_tuple = (1, 2, 3)
print(my_tuple)  # Output: (1, 2, 3)

# Tuples can also be created without parentheses
another_tuple = 4, 5, 6
print(another_tuple)  # Output: (4, 5, 6)

# Creating an empty tuple
empty_tuple = ()
print(empty_tuple)  # Output: ()

# Creating a tuple with a single item
single_item_tuple = (7,)
print(single_item_tuple)  # Output: (7,)
Enter fullscreen mode Exit fullscreen mode

Accessing Tuple Elements

Elements in a tuple can be accessed using indexing, just like lists. Indices start at 0.

my_tuple = (1, 2, 3, 4, 5)

# Accessing elements
print(my_tuple[0])  # Output: 1
print(my_tuple[3])  # Output: 4

# Negative indexing
print(my_tuple[-1])  # Output: 5
print(my_tuple[-2])  # Output: 4
Enter fullscreen mode Exit fullscreen mode

Slicing Tuples

You can slice tuples to create a new tuple that contains a subset of the original elements.

my_tuple = (1, 2, 3, 4, 5)

# Slicing
print(my_tuple[1:3])   # Output: (2, 3)
print(my_tuple[:2])    # Output: (1, 2)
print(my_tuple[2:])    # Output: (3, 4, 5)
print(my_tuple[-3:-1]) # Output: (3, 4)
Enter fullscreen mode Exit fullscreen mode

Unpacking Tuples

Tuples can be unpacked into individual variables. The number of variables must match the number of elements in the tuple.

my_tuple = (1, 2, 3)

# Unpacking
a, b, c = my_tuple
print(a)  # Output: 1
print(b)  # Output: 2
print(c)  # Output: 3

# Unpacking with *
my_tuple = (1, 2, 3, 4, 5)
a, *b, c = my_tuple
print(a)  # Output: 1
print(b)  # Output: [2, 3, 4]
print(c)  # Output: 5
Enter fullscreen mode Exit fullscreen mode

Nested Tuples

Tuples can contain other tuples as elements, creating a nested structure.

nested_tuple = (1, (2, 3), (4, (5, 6)))
print(nested_tuple)  # Output: (1, (2, 3), (4, (5, 6)))

# Accessing nested elements
print(nested_tuple[1])       # Output: (2, 3)
print(nested_tuple[2][1])    # Output: (5, 6)
print(nested_tuple[2][1][0]) # Output: 5
Enter fullscreen mode Exit fullscreen mode

Tuple Operations

Tuples support various operations, such as concatenation and repetition.

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

# Concatenation
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple)  # Output: (1, 2, 3, 4, 5, 6)

# Repetition
repeated_tuple = tuple1 * 2
print(repeated_tuple)  # Output: (1, 2, 3, 1, 2, 3)
Enter fullscreen mode Exit fullscreen mode

Tuple Membership

You can check if an item is present in a tuple using the in keyword.

my_tuple = (1, 2, 3, 4, 5)

# Membership check
print(3 in my_tuple)  # Output: True
print(6 in my_tuple)  # Output: False
Enter fullscreen mode Exit fullscreen mode

Length of a Tuple

You can find out the number of items in a tuple using the len() function.

my_tuple = (1, 2, 3, 4, 5)

# Length of the tuple
print(len(my_tuple))  # Output: 5
Enter fullscreen mode Exit fullscreen mode

Tuple Immutability

Once a tuple is created, its contents cannot be modified. This immutability can be useful to ensure that the data remains unchanged throughout the program.

my_tuple = (1, 2, 3)

# Trying to change a value will raise an error
# my_tuple[0] = 4  # TypeError: 'tuple' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

Tuples as Dictionary Keys

Because tuples are immutable, they can be used as keys in dictionaries, unlike lists.

my_dict = {(1, 2): "value1", (3, 4): "value2"}
print(my_dict)  # Output: {(1, 2): 'value1', (3, 4): 'value2'}

# Accessing values
print(my_dict[(1, 2)])  # Output: value1
Enter fullscreen mode Exit fullscreen mode

Tuple Methods in Python

Counting Elements

count

  • Returns the number of times the specified item appears in the tuple.
  • Syntax: tuple.count(item)
my_tuple = (1, 2, 3, 2, 2, 4)
count_twos = my_tuple.count(2)
print(count_twos)  # Output: 3
Enter fullscreen mode Exit fullscreen mode

Finding Index

index

  • Returns the index of the first item whose value is equal to the specified value.
  • Syntax: tuple.index(item, [start, [end]])
my_tuple = (1, 2, 3, 2, 4)
index_of_two = my_tuple.index(2)
print(index_of_two)  # Output: 1

index_of_two_from_2 = my_tuple.index(2, 2)
print(index_of_two_from_2)  # Output: 3
Enter fullscreen mode Exit fullscreen mode

Dictionaries in Python

Dictionaries are a type of collection in Python that store data in key-value pairs. They are unordered, changeable, and do not allow duplicate keys. Dictionaries are optimized for retrieving data when the key is known.

Creating Dictionaries

You can create a dictionary using curly braces {} with key-value pairs separated by a colon :.

# Creating an empty dictionary
empty_dict = {}

# Creating a dictionary with some key-value pairs
my_dict = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
print(my_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

# Creating a dictionary using the dict() constructor
another_dict = dict(name="Jane", age=25, city="Chicago")
print(another_dict)  # Output: {'name': 'Jane', 'age': 25, 'city': 'Chicago'}
Enter fullscreen mode Exit fullscreen mode

Accessing Dictionary Elements

You can access the value associated with a specific key using square brackets [] or the get method.

my_dict = {"name": "John", "age": 30, "city": "New York"}

# Accessing values
print(my_dict["name"])  # Output: John
print(my_dict.get("age"))  # Output: 30

# Accessing a key that doesn't exist
print(my_dict.get("address"))  # Output: None
Enter fullscreen mode Exit fullscreen mode

Adding and Modifying Elements

You can add new key-value pairs or modify existing ones by assigning a value to a key.

my_dict = {"name": "John", "age": 30, "city": "New York"}

# Adding a new key-value pair
my_dict["email"] = "john@example.com"
print(my_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'email': 'john@example.com'}

# Modifying an existing key-value pair
my_dict["age"] = 31
print(my_dict)  # Output: {'name': 'John', 'age': 31, 'city': 'New York', 'email': 'john@example.com'}
Enter fullscreen mode Exit fullscreen mode

Removing Elements

You can remove elements from a dictionary using the del statement or the pop method.

my_dict = {"name": "John", "age": 30, "city": "New York", "email": "john@example.com"}

# Removing a key-value pair using del
del my_dict["email"]
print(my_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

# Removing a key-value pair using pop
age = my_dict.pop("age")
print(age)  # Output: 30
print(my_dict)  # Output: {'name': 'John', 'city': 'New York'}
Enter fullscreen mode Exit fullscreen mode

Checking for Keys

You can check if a key exists in a dictionary using the in keyword.

my_dict = {"name": "John", "age": 30, "city": "New York"}

# Checking for a key
print("name" in my_dict)  # Output: True
print("email" in my_dict)  # Output: False
Enter fullscreen mode Exit fullscreen mode

Looping Through a Dictionary

You can loop through a dictionary to access keys, values, or both.

my_dict = {"name": "John", "age": 30, "city": "New York"}

# Looping through keys
for key in my_dict:
    print(key)

# Looping through values
for value in my_dict.values():
    print(value)

# Looping through key-value pairs
for key, value in my_dict.items():
    print(key, value)
Enter fullscreen mode Exit fullscreen mode

Nested Dictionaries

Dictionaries can contain other dictionaries, creating a nested structure.

nested_dict = {
    "person1": {"name": "John", "age": 30},
    "person2": {"name": "Jane", "age": 25}
}

# Accessing nested dictionary values
print(nested_dict["person1"]["name"])  # Output: John
print(nested_dict["person2"]["age"])   # Output: 25
Enter fullscreen mode Exit fullscreen mode

Dictionary Comprehensions

You can create dictionaries using dictionary comprehensions, which are concise ways to generate dictionaries.

# Dictionary comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Enter fullscreen mode Exit fullscreen mode

Merging Dictionaries

You can merge two dictionaries using the update method or the | operator (Python 3.9+).

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

# Merging using update
dict1.update(dict2)
print(dict1)  # Output: {'a': 1, 'b': 3, 'c': 4}

# Merging using the | operator (Python 3.9+)
dict3 = dict1 | dict2
print(dict3)  # Output: {'a': 1, 'b': 3, 'c': 4}
Enter fullscreen mode Exit fullscreen mode

Dictionary Methods in Python

Clearing and Copying

clear

  • Removes all elements from the dictionary.
  • Syntax: dictionary.clear()
my_dict = {"name": "John", "age": 30}
my_dict.clear()
print(my_dict)  # Output: {}
Enter fullscreen mode Exit fullscreen mode

copy

  • Returns a shallow copy of the dictionary.
  • Syntax: dictionary.copy()
my_dict = {"name": "John", "age": 30}
copy_dict = my_dict.copy()
print(copy_dict)  # Output: {'name': 'John', 'age': 30}
Enter fullscreen mode Exit fullscreen mode

Creating from Keys

fromkeys

  • Creates a new dictionary with keys from an iterable and values set to a specified value.
  • Syntax: dict.fromkeys(iterable, value=None)
keys = ('name', 'age', 'city')
value = 'unknown'
new_dict = dict.fromkeys(keys, value)
print(new_dict)  # Output: {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}
Enter fullscreen mode Exit fullscreen mode

Accessing Elements

get

  • Returns the value for the specified key if the key is in the dictionary; otherwise, returns a default value.
  • Syntax: dictionary.get(key, default=None)
my_dict = {"name": "John", "age": 30}
print(my_dict.get("name"))  # Output: John
print(my_dict.get("address", "Not Found"))  # Output: Not Found
Enter fullscreen mode Exit fullscreen mode

Retrieving Dictionary Views

items

  • Returns a view object that displays a list of a dictionary's key-value tuple pairs.
  • Syntax: dictionary.items()
my_dict = {"name": "John", "age": 30}
print(my_dict.items())  # Output: dict_items([('name', 'John'), ('age', 30)])
Enter fullscreen mode Exit fullscreen mode

keys

  • Returns a view object that displays a list of all the keys in the dictionary.
  • Syntax: dictionary.keys()
my_dict = {"name": "John", "age": 30}
print(my_dict.keys())  # Output: dict_keys(['name', 'age'])
Enter fullscreen mode Exit fullscreen mode

values

  • Returns a view object that displays a list of all the values in the dictionary.
  • Syntax: dictionary.values()
my_dict = {"name": "John", "age": 30}
print(my_dict.values())  # Output: dict_values(['John', 30])
Enter fullscreen mode Exit fullscreen mode

Removing Elements

pop

  • Removes the specified key and returns the corresponding value. If the key is not found, it returns a default value if provided.
  • Syntax: dictionary.pop(key, default=None)
my_dict = {"name": "John", "age": 30}
age = my_dict.pop("age")
print(age)  # Output: 30
print(my_dict)  # Output: {'name': 'John'}
Enter fullscreen mode Exit fullscreen mode

popitem

  • Removes and returns the last inserted key-value pair as a tuple. It raises a KeyError if the dictionary is empty.
  • Syntax: dictionary.popitem()
my_dict = {"name": "John", "age": 30}
last_item = my_dict.popitem()
print(last_item)  # Output: ('age', 30)
print(my_dict)  # Output: {'name': 'John'}
Enter fullscreen mode Exit fullscreen mode

Setting Default Values

setdefault

  • Returns the value of the specified key. If the key does not exist, inserts the key with the specified value.
  • Syntax: dictionary.setdefault(key, default=None)
my_dict = {"name": "John", "age": 30}
age = my_dict.setdefault("age", 25)
print(age)  # Output: 30
city = my_dict.setdefault("city", "New York")
print(city)  # Output: New York
print(my_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
Enter fullscreen mode Exit fullscreen mode

Updating Dictionaries

update

  • Updates the dictionary with elements from another dictionary object or from an iterable of key-value pairs.
  • Syntax: dictionary.update([other])
my_dict = {"name": "John", "age": 30}
new_data = {"age": 31, "city": "New York"}
my_dict.update(new_data)
print(my_dict)  # Output: {'name': 'John', 'age': 31, 'city': 'New York'}
Enter fullscreen mode Exit fullscreen mode

Additional Methods

len

  • Returns the number of key-value pairs in the dictionary.
  • Syntax: len(dictionary)
my_dict = {"name": "John", "age": 30}
print(len(my_dict))  # Output: 2
Enter fullscreen mode Exit fullscreen mode

del

  • Deletes a key-value pair from the dictionary.
  • Syntax: del dictionary[key]
my_dict = {"name": "John", "age": 30}
del my_dict["age"]
print(my_dict)  # Output: {'name': 'John'}
Enter fullscreen mode Exit fullscreen mode

Sets in Python

Sets are an unordered collection of unique items in Python. They are useful for storing elements where duplication is not allowed and for performing various mathematical set operations like union, intersection, difference, and symmetric difference.

Creating Sets

You can create a set using curly braces {} or the set() function.

# Using curly braces
my_set = {1, 2, 3}
print(my_set)  # Output: {1, 2, 3}

# Using the set() function
my_set = set([1, 2, 3])
print(my_set)  # Output: {1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

Adding Elements

You can add elements to a set using the add method.

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # Output: {1, 2, 3, 4}
Enter fullscreen mode Exit fullscreen mode

Removing Elements

You can remove elements using the remove or discard methods. The difference is that remove will raise a KeyError if the element is not found, whereas discard will not.

my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)  # Output: {1, 3}

my_set.discard(4)  # No error even if 4 is not in the set
print(my_set)  # Output: {1, 3}
Enter fullscreen mode Exit fullscreen mode

Checking Membership

You can check if an element is a member of a set using the in keyword.

my_set = {1, 2, 3}
print(1 in my_set)  # Output: True
print(4 in my_set)  # Output: False
Enter fullscreen mode Exit fullscreen mode

Iterating Through a Set

You can iterate through a set using a for loop.

my_set = {1, 2, 3}
for item in my_set:
    print(item)
# Output:
# 1
# 2
# 3
Enter fullscreen mode Exit fullscreen mode

Set Comprehensions

Like list comprehensions, you can use set comprehensions to create sets.

my_set = {x * x for x in range(5)}
print(my_set)  # Output: {0, 1, 4, 9, 16}
Enter fullscreen mode Exit fullscreen mode

Frozen Sets

A frozenset is an immutable version of a set. You can create a frozenset using the frozenset() function.

my_set = frozenset([1, 2, 3])
print(my_set)  # Output: frozenset({1, 2, 3})
Enter fullscreen mode Exit fullscreen mode

Set Methods in Python

Adding Elements

add

  • Adds an element to the set.
  • Syntax: set.add(element)
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # Output: {1, 2, 3, 4}
Enter fullscreen mode Exit fullscreen mode

Clearing and Copying

clear

  • Removes all elements from the set.
  • Syntax: set.clear()
my_set = {1, 2, 3}
my_set.clear()
print(my_set)  # Output: set()
Enter fullscreen mode Exit fullscreen mode

copy

  • Returns a shallow copy of the set.
  • Syntax: set.copy()
my_set = {1, 2, 3}
copy_set = my_set.copy()
print(copy_set)  # Output: {1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

Difference and Update

difference

  • Returns a new set with elements that are in the set but not in another set.
  • Syntax: set.difference(other_set)
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
diff_set = set1.difference(set2)
print(diff_set)  # Output: {1, 2}
Enter fullscreen mode Exit fullscreen mode

difference_update

  • Removes all elements of another set from this set.
  • Syntax: set.difference_update(other_set)
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
set1.difference_update(set2)
print(set1)  # Output: {1, 2}
Enter fullscreen mode Exit fullscreen mode

Discarding Elements

discard

  • Removes an element from the set if it is a member.
  • Syntax: set.discard(element)
my_set = {1, 2, 3}
my_set.discard(2)
print(my_set)  # Output: {1, 3}
Enter fullscreen mode Exit fullscreen mode

Intersection and Update

intersection

  • Returns a new set with elements that are common to this set and another.
  • Syntax: set.intersection(other_set)
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection_set = set1.intersection(set2)
print(intersection_set)  # Output: {2, 3}
Enter fullscreen mode Exit fullscreen mode

intersection_update

  • Updates the set with the intersection of itself and another.
  • Syntax: set.intersection_update(other_set)
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set1.intersection_update(set2)
print(set1)  # Output: {2, 3}
Enter fullscreen mode Exit fullscreen mode

Set Relations

isdisjoint

  • Returns True if two sets have no common elements.
  • Syntax: set.isdisjoint(other_set)
set1 = {1, 2}
set2 = {3, 4}
print(set1.isdisjoint(set2))  # Output: True
Enter fullscreen mode Exit fullscreen mode

issubset

  • Returns True if another set contains this set.
  • Syntax: set.issubset(other_set)
set1 = {1, 2}
set2 = {1, 2, 3, 4}
print(set1.issubset(set2))  # Output: True
Enter fullscreen mode Exit fullscreen mode

issuperset

  • Returns True if this set contains another set.
  • Syntax: set.issuperset(other_set)
set1 = {1, 2, 3, 4}
set2 = {1, 2}
print(set1.issuperset(set2))  # Output: True
Enter fullscreen mode Exit fullscreen mode

Removing Elements

pop

  • Removes and returns an arbitrary element from the set. Raises KeyError if the set is empty.
  • Syntax: set.pop()
my_set = {1, 2, 3}
elem = my_set.pop()
print(elem)  # Output: 1 (this will vary as it's arbitrary)
print(my_set)  # Output: {2, 3}
Enter fullscreen mode Exit fullscreen mode

remove

  • Removes the specified element from the set.
  • Syntax: set.remove(element)
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)  # Output: {1, 3}
Enter fullscreen mode Exit fullscreen mode

Symmetric Difference and Update

symmetric_difference

  • Returns a new set with elements in either set but not both.
  • Syntax: set.symmetric_difference(other_set)
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
sym_diff_set = set1.symmetric_difference(set2)
print(sym_diff_set)  # Output: {1, 2, 5}
Enter fullscreen mode Exit fullscreen mode

symmetric_difference_update

  • Updates the set with the symmetric difference of itself and another.
  • Syntax: set.symmetric_difference_update(other_set)
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
set1.symmetric_difference_update(set2)
print(set1)  # Output: {1, 2, 5}
Enter fullscreen mode Exit fullscreen mode

Union and Update

union

  • Returns a new set with elements from the set and another set.
  • Syntax: set.union(other_set)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)  # Output: {1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

update

  • Updates the set with elements from itself and another set or iterable.
  • Syntax: set.update([other_set])
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1)  # Output: {1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

Additional Methods and Operations

Shortcut Operations (-= &= <= < >= > ^ ^= | |=)

  • set -= other_set: Removes all elements of other_set from set.
  • set &= other_set: Updates set with the intersection of itself and other_set.
  • set <= other_set: Returns True if every element in set is in other_set.
  • set < other_set: Returns True if set is a proper subset of other_set.
  • set >= other_set: Returns True if every element in other_set is in set.
  • set > other_set: Returns True if set is a proper superset of other_set.
  • set ^= other_set: Updates set with the symmetric difference of itself and other_set.
  • set |= other_set: Updates set with elements from other_set.
set1 = {1, 2, 3}
set2 = {2, 3, 4}

set1 -= {2}
print(set1)  # Output: {1, 3}

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

print(set1 <= set2)  # Output: True
print(set1 < set2)   # Output: True
print(set1 >= set2)  # Output: False
print(set1 > set2)   # Output: False

set1 ^= {3, 4, 5}
print(set1)  # Output: {4, 5}

set1 |= {1, 2}
print(set1)  # Output: {1, 2, 4, 5}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .