python basics sets

Save (0)
Close

Recommended

Description

Python is a high-level programming language that offers various data structures to store and manipulate different types of data. Two of these important data structures in Python are Dictionary and Set.

Dictionary:
A dictionary in Python is a collection of key-value pairs, where each key is unique, and associated with a value. Dictionaries are created by enclosing a comma-separated list of key-value pairs within curly braces ({}).

Example:

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

Here, the keys are ‘name’, ‘age’, and ‘city’, and the corresponding values are ‘John’, 30, and ‘New York’.

To access the value associated with a particular key, we can use the square brackets ([]).

Example:

name = my_dict[‘name’]

In this example, the value of the ‘name’ key, i.e., ‘John’, will be stored in the variable ‘name’.

We can also modify the value associated with a particular key using the same square bracket notation.

Example:

my_dict[‘city’] = ‘Chicago’

In this example, the value associated with the ‘city’ key will be changed from ‘New York’ to ‘Chicago’.

Set:
A set in Python is an unordered collection of unique elements. Sets are created using the set() function or by enclosing a comma-separated list of elements within curly braces ({}).

Example:

my_set = {1, 2, 3, 4, 5}

Here, the set contains the elements 1, 2, 3, 4, and 5.

We can perform various mathematical operations on sets, such as union, intersection, and difference.

Example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
union_set = set1.union(set2) # union of two sets
print(union_set)
intersection_set = set1.intersection(set2) # intersection of two sets
print(intersection_set)
difference_set = set1.difference(set2) # difference of two sets
print(difference_set)

In this example, the ‘union_set’ will contain the elements 1, 2, 3, and 4, the ‘intersection_set’ will contain the elements 2 and 3, and the ‘difference_set’ will contain the elements 1.

We can also add or remove elements from a set using the add(), remove(), or discard() methods.

Example:

my_set.add(6) # add an element to the set
my_set.remove(3) # remove an element from the set
my_set.discard(7) # remove an element if exists, or do nothing if it does not exist.

In this example, the ‘add()’ method will add the element 6 to the