# Lists, Tuples, Sets, Dictionaries

{% embed url="<https://www.youtube.com/watch?v=W8KRzm-HUcc>" %}

## Lists in Python&#x20;

In this article, we'll learn everything about Python lists, how they are created, slicing of a list, adding or removing elements from them and so on. List is one of the most frequently used and very versatile data types used in Python.&#x20;

### How to create a list?&#x20;

In Python programming, a list is created by placing all the items (elements) inside square brackets \[] , separated by commas.

It can have any number of items and they may be of different types (integer, float, string etc.)

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQKwCH-NdFIASqvbGa%2F-MjQMApHVgWAD2-s8XIR%2FSchermafbeelding%202021-09-12%20205442.jpeg?alt=media\&token=a1d78bd7-b33f-4db6-a503-7f987dfee0a6)

A list can also have another list as an item. This is called a nested list.

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQKwCH-NdFIASqvbGa%2F-MjQMJ-YFzA92ZXcKJSt%2FSchermafbeelding%202021-09-12%20205518.jpeg?alt=media\&token=8c4fbeda-4c54-445e-9465-5efc3edc15e2)

### How to access elements from a list?

There are various ways in which we can access the elements of a list

### List Index

&#x20;We can use the index operator \[] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.&#x20;

Trying to access indexes other than these will raise an IndexError . The index must be an integer. We can't use float or other types, this will result in TypeError.&#x20;

Nested lists are accessed using nested indexing.

{% tabs %}
{% tab title="Python" %}

```python
# List indexing

my_list = ['p', 'r', 'o', 'b', 'e']

# Output: p
print(my_list[0])

# Output: o
print(my_list[2])

# Output: e
print(my_list[4])

# Nested List
n_list = ["Happy", [2, 0, 1, 5]]

# Nested indexing
print(n_list[0][1])

print(n_list[1][3])

# Error! Only integer can be used for indexing
print(my_list[4.0])

```

{% endtab %}

{% tab title="Output" %}

```
p
o
e
a
5
Traceback (most recent call last):
  File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float

```

{% endtab %}
{% endtabs %}

### Negative indexing&#x20;

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

{% tabs %}
{% tab title="Python" %}

```python
# Negative indexing in lists
my_list = ['p','r','o','b','e']

print(my_list[-1])

print(my_list[-5])

```

{% endtab %}

{% tab title="Output" %}

```
e
p

```

{% endtab %}
{% endtabs %}

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQKwCH-NdFIASqvbGa%2F-MjQN_q5ptcz6_JeF-_A%2FSchermafbeelding%202021-09-12%20210014.jpeg?alt=media\&token=e181221e-ae7e-410b-ba07-173cd3f6fe99)

### How to slice lists in Python?&#x20;

We can access a range of items in a list by using the slicing operator : (colon).

{% tabs %}
{% tab title="Python" %}

```python
:(colon).
# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# elements 3rd to 5th
print(my_list[2:5])

# elements beginning to 4th
print(my_list[:-5])

# elements 6th to end
print(my_list[5:])

# elements beginning to end
print(my_list[:])

```

{% endtab %}

{% tab title="Ouput" %}

```
['o', 'g', 'r']
['p', 'r', 'o', 'g']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

```

{% endtab %}
{% endtabs %}

Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need two indices that will slice that portion from the list.&#x20;

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQNqC-kUCoUG6-Of_X%2F-MjQOO2Ob7mrx5R9lyvH%2FSchermafbeelding%202021-09-12%20210413.jpeg?alt=media\&token=66df0c98-fc0e-4f82-93a7-6c7fcb222a7d)

### **Add/Change List Elements**

Lists are mutable, meaning their elements can be changed unlike string or tuple.&#x20;

We can use the assignment operator ( = ) to change an item or a range of items.

{% tabs %}
{% tab title="Python" %}

```python
# Correcting mistake values in a list
odd = [2, 4, 6, 8]

# change the 1st item    
odd[0] = 1            

print(odd)

# change 2nd to 4th items
odd[1:4] = [3, 5, 7]  

print(odd)     
```

{% endtab %}

{% tab title="Output" %}

```
[1, 4, 6, 8]
[1, 3, 5, 7]

```

{% endtab %}
{% endtabs %}

We can add one item to a list using the append() method or add several items using extend() method.

{% tabs %}
{% tab title="Python" %}

```python
# Appending and Extending lists in Python
odd = [1, 3, 5]

odd.append(7)

print(odd)

odd.extend([9, 11, 13])

print(odd)

```

{% endtab %}

{% tab title="Output" %}

```
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]

```

{% endtab %}
{% endtabs %}

We can also use + operator to combine two lists. This is also called concatenation.&#x20;

The \* operator repeats a list for the given number of times.

{% tabs %}
{% tab title="Python" %}

```python
# Concatenating and repeating lists
odd = [1, 3, 5]

print(odd + [9, 7, 5])

print(["re"] * 3)
```

{% endtab %}

{% tab title="Output" %}

```
[1, 3, 5, 9, 7, 5]
['re', 're', 're']

```

{% endtab %}
{% endtabs %}

Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.

{% tabs %}
{% tab title="Python" %}

```python
# Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)

print(odd)

odd[2:2] = [5, 7]

print(odd)

```

{% endtab %}

{% tab title="Output" %}

```
[1, 3, 9]
[1, 3, 5, 7, 9]

```

{% endtab %}
{% endtabs %}

### **Delete/Remove List Elements**

We can delete one or more items from a list using the keyword del . It can even delete the list entirely

{% tabs %}
{% tab title="Python" %}

```python
# Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# delete one item
del my_list[2]

print(my_list)

# delete multiple items
del my_list[1:5]

print(my_list)

# delete entire list
del my_list

# Error: List not defined
print(my_list)

```

{% endtab %}

{% tab title="Output" %}

```
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
Traceback (most recent call last):
  File "<string>", line 18, in <module>
NameError: name 'my_list' is not defined

```

{% endtab %}
{% endtabs %}

We can use remove() method to remove the given item or pop() method to remove an item at the given index.

&#x20;The pop() method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure).&#x20;

We can also use the clear() method to empty a list.

{% tabs %}
{% tab title="Python" %}

```python
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')

# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)

# Output: 'o'
print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)

# Output: 'm'
print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']
print(my_list)

my_list.clear()

# Output: []
print(my_list)
```

{% endtab %}

{% tab title="Output" %}

```
['r', 'o', 'b', 'l', 'e', 'm']
o
['r', 'b', 'l', 'e', 'm']
m
['r', 'b', 'l', 'e']
[]

```

{% endtab %}
{% endtabs %}

Finally, we can also delete items in a list by assigning an empty list to a slice of elements.

```python
>>> my_list = ['p','r','o','b','l','e','m']
>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']

```

## Python List Methods

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQQIXcTqRqrkg3rIi9%2F-MjQQRX_WBgfrzHj3YhM%2FSchermafbeelding%202021-09-12%20211319.jpeg?alt=media\&token=de4640e3-b16d-41de-8303-80923ac0dfe5)

**Some examples of Python list methods:**\\

{% tabs %}
{% tab title="Python" %}

```python
# Python list methods
my_list = [3, 8, 1, 6, 0, 8, 4]

# Output: 1
print(my_list.index(8))

# Output: 2
print(my_list.count(8))

my_list.sort()

# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)

my_list.reverse()

# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)
```

{% endtab %}

{% tab title="Output" %}

```
1
2
[0, 1, 3, 4, 6, 8, 8]
[8, 8, 6, 4, 3, 1, 0]

```

{% endtab %}
{% endtabs %}

### **List Comprehension: Elegant way to create Lists**

List comprehension is an elegant and concise way to create a new list from an existing list in Python.

A list comprehension consists of an expression followed by [for statement](https://www.programiz.com/python-programming/for-loop) inside square brackets.

Here is an example to make a list with each item being increasing power of 2.\
\\

{% tabs %}
{% tab title="Python" %}

```python
pow2 = [2 ** x for x in range(10)]
print(pow2)

```

{% endtab %}

{% tab title="Output" %}

```
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
```

{% endtab %}
{% endtabs %}

This code is equivalent to:

```python
pow2 = []
for x in range(10):
   pow2.append(2 ** x)

```

A list comprehension can optionally contain more for or [if statements](https://www.programiz.com/python-programming/if-elif-else). An optional if statement can filter out items for the new list. Here are some examples.

```python
>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']

```

### **Other List Operations in Python**

#### **List Membership Test**

We can test if an item exists in a list or not, using the keyword i&#x6E;**.**

{% tabs %}
{% tab title="Python" %}

```python
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# Output: True
print('p' in my_list)

# Output: False
print('a' in my_list)

# Output: True
print('c' not in my_list)

```

{% endtab %}

{% tab title="Output" %}

```
True
False
True

```

{% endtab %}
{% endtabs %}

#### **Iterating Through a List**

Using a for loop we can iterate through each item in a list.

{% tabs %}
{% tab title="Python" %}

```python
for fruit in ['apple','banana','mango']:
    print("I like",fruit)

```

{% endtab %}

{% tab title="Output" %}

```
I like apple
I like banana
I like mango

```

{% endtab %}
{% endtabs %}

## **Python Tuple**

In this article, you'll learn everything about Python tuples. More specifically, what are tuples, how to create them, when to use them and various methods you should be familiar with.

&#x20;A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list.&#x20;

### Creating a Tuple&#x20;

A tuple is created by placing all the items (elements) inside parentheses () , separated by commas. The parentheses are optional, however, it is a good practice to use them.&#x20;

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

{% tabs %}
{% tab title="Python" %}

```python
# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

```

{% endtab %}

{% tab title="Output" %}

```
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

```

{% endtab %}
{% endtabs %}

A tuple can also be created without using parentheses. This is known as tuple packing.

{% tabs %}
{% tab title="Python" %}

```python
my_tuple = 3, 4.6, "dog"
print(my_tuple)

# tuple unpacking is also possible
a, b, c = my_tuple

print(a)      # 3
print(b)      # 4.6
print(c)      # dog

```

{% endtab %}

{% tab title="Output" %}

```
(3, 4.6, 'dog')
3
4.6
dog

```

{% endtab %}
{% endtabs %}

Creating a tuple with one element is a bit tricky.

&#x20;Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in fact, a tuple.

{% tabs %}
{% tab title="Python" %}

```python
my_tuple = ("hello")
print(type(my_tuple))  # <class 'str'>

# Creating a tuple having one element
my_tuple = ("hello",)
print(type(my_tuple))  # <class 'tuple'>

# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple))  # <class 'tuple'>

```

{% endtab %}

{% tab title="Output" %}

```
<class 'str'>
<class 'tuple'>
<class 'tuple'>

```

{% endtab %}
{% endtabs %}

### Access Tuple Elements&#x20;

There are various ways in which we can access the elements of a tuple.&#x20;

#### 1.Indexing&#x20;

We can use the index operator \[] to access an item in a tuple, where the index starts from 0.&#x20;

So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range(6,7,... in this example) will raise an IndexError .&#x20;

The index must be an integer, so we cannot use float or other types. This will result in TypeError .&#x20;

Likewise, nested tuples are accessed using nested indexing, as shown in the example below.

{% tabs %}
{% tab title="Python" %}

```python
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0])   # 'p' 
print(my_tuple[5])   # 't'

# IndexError: list index out of range
# print(my_tuple[6])

# Index must be an integer
# TypeError: list indices must be integers, not float
# my_tuple[2.0]

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3])       # 's'
print(n_tuple[1][1])       # 4
```

{% endtab %}

{% tab title="Output" %}

```
p
t
s
4

```

{% endtab %}
{% endtabs %}

#### **2.**&#x4E;egative Indexing

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

{% tabs %}
{% tab title="Python" %}

```python
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])
```

{% endtab %}

{% tab title="Output" %}

```
t
p

```

{% endtab %}
{% endtabs %}

#### 3.Slicing

We can access a range of items in a tuple by using the slicing operator colon:

{% tabs %}
{% tab title="Python" %}

```python
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m','i','z')

# elements 2nd to 4th
# Output: ('r', 'o', 'g')
print(my_tuple[1:4])

# elements beginning to 2nd
# Output: ('p', 'r')
print(my_tuple[:-7])

# elements 8th to end
# Output: ('i', 'z')
print(my_tuple[7:])

# elements beginning to end
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])

```

{% endtab %}

{% tab title="Output" %}

```
('r', 'o', 'g')
('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

```

{% endtab %}
{% endtabs %}

Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need the index that will slice the portion from the tuple.

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQQIXcTqRqrkg3rIi9%2F-MjQV1kNhNc3St7ClcZf%2FSchermafbeelding%202021-09-12%20213324.jpeg?alt=media\&token=48538107-e47e-4c1f-9a1f-a336d2f642f0)

### Changing a Tuple&#x20;

Unlike lists, tuples are immutable.&#x20;

This means that elements of a tuple cannot be changed once they have been assigned. But, if the element is itself a mutable data type like list, its nested items can be changed.&#x20;

We can also assign a tuple to different values (reassignment).

{% tabs %}
{% tab title="Python" %}

```python
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])


# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9

# However, item of mutable element can be changed
my_tuple[3][0] = 9    # Output: (4, 2, 3, [9, 5])
print(my_tuple)

# Tuples can be reassigned
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)

```

{% endtab %}

{% tab title="Output" %}

```
(4, 2, 3, [9, 5])
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

```

{% endtab %}
{% endtabs %}

We can use + operator to combine two tuples. This is called concatenation .&#x20;

We can also repeat the elements in a tuple for a given number of times using the *operator.*&#x20;

*Both + and* operations result in a new tuple

{% tabs %}
{% tab title="Python" %}

```python
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))

# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)


```

{% endtab %}

{% tab title="Output" %}

```
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')

```

{% endtab %}
{% endtabs %}

### Deleting a Tuple&#x20;

As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a tuple.&#x20;

Deleting a tuple entirely, however, is possible using the keyword del .

{% tabs %}
{% tab title="Python" %}

```python
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# can't delete items
# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]

# Can delete an entire tuple
del my_tuple

# NameError: name 'my_tuple' is not defined
print(my_tuple)

```

{% endtab %}

{% tab title="Output" %}

```
Traceback (most recent call last):
  File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined

```

{% endtab %}
{% endtabs %}

### Tuple Methods&#x20;

Methods that add items or remove items are not available with tuple. Only the following two methods are available.&#x20;

Some examples of Python tuple methods:

{% tabs %}
{% tab title="Python" %}

```python
my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p'))  # Output: 2
print(my_tuple.index('l'))  # Output: 3

```

{% endtab %}

{% tab title="Output" %}

```
2
3

```

{% endtab %}
{% endtabs %}

### **Other Tuple Operations**

#### **1. Tuple Membership Test**

**We can test if an item exists in a tuple or not, using the keyword in**

{% tabs %}
{% tab title="Python" %}

```python
# Membership test in tuple
my_tuple = ('a', 'p', 'p', 'l', 'e',)

# In operation
print('a' in my_tuple)
print('b' in my_tuple)

# Not in operation
print('g' not in my_tuple)
```

{% endtab %}

{% tab title="Output" %}

```
True
False
True

```

{% endtab %}
{% endtabs %}

#### **2. Iterating Through a Tuple**

**We can use a for loop to iterate through each item in a tuple.**\\

{% tabs %}
{% tab title="Python" %}

```python
# Using a for loop to iterate through a tuple
for name in ('John', 'Kate'):
    print("Hello", name)

```

{% endtab %}

{% tab title="Output" %}

```
Hello John
Hello Kate

```

{% endtab %}
{% endtabs %}

### Advantages of Tuple over List

&#x20;Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages:&#x20;

* We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types.&#x20;
* Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight performance boost.&#x20;
* Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible.&#x20;
* If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.

## **Python Sets**

In this tutorial, you'll learn everything about Python sets; how they are created, adding or removing elements from them, and all operations performed on sets in Python.

A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed).

However, a set itself is mutable. We can add or remove items from it.

Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.\\

### **Creating Python Sets**

A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function.

It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like [lists](https://www.programiz.com/python-programming/list), sets or [dictionaries](https://www.programiz.com/python-programming/dictionary) as its elements.

{% tabs %}
{% tab title="Python" %}

```python
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

```

{% endtab %}

{% tab title="Output" %}

```
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}

```

{% endtab %}
{% endtabs %}

**Try the following examples as well.**\\

{% tabs %}
{% tab title="Python" %}

```python
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)

# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)

# set cannot have mutable items
# here [3, 4] is a mutable list
# this will cause an error.

my_set = {1, 2, [3, 4]}

```

{% endtab %}

{% tab title="Output" %}

```
{1, 2, 3, 4}
{1, 2, 3}
Traceback (most recent call last):
  File "<string>", line 15, in <module>
    my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'

```

{% endtab %}
{% endtabs %}

Creating an empty set is a bit tricky.

Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements, we use the set() function without any argument.

{% tabs %}
{% tab title="Python" %}

```python
# Distinguish set and dictionary while creating empty set

# initialize a with {}
a = {}

# check data type of a
print(type(a))

# initialize a with set()
a = set()

# check data type of a
print(type(a))

```

{% endtab %}

{% tab title="Output" %}

```
<class 'dict'>
<class 'set'>

```

{% endtab %}
{% endtabs %}

### Modifying a set in Python&#x20;

Sets are mutable. However, since they are unordered, indexing has no meaning.&#x20;

We cannot access or change an element of a set using indexing or slicing. Set data type does not support it.&#x20;

We can add a single element using the add() method, and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.

{% tabs %}
{% tab title="Python" %}

```python
# initialize my_set
my_set = {1, 3}
print(my_set)

# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing

# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)

# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)

# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)

```

{% endtab %}

{% tab title="Output" %}

```
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}

```

{% endtab %}
{% endtabs %}

### **Removing elements from a set**

A particular item can be removed from a set using the methods discard() and remove().

The only difference between the two is that the discard() function leaves a set unchanged if the element is not present in the set. On the other hand, the remove() function will raise an error in such a condition (if element is not present in the set).

The following example will illustrate this.

{% tabs %}
{% tab title="Python" %}

```python
# Difference between discard() and remove()

# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)

# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)

# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)

# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)

# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError

my_set.remove(2)
```

{% endtab %}

{% tab title="Output" %}

```
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
  File "<string>", line 28, in <module>
KeyError: 2

```

{% endtab %}
{% endtabs %}

Similarly, we can remove and return an item using the pop() method.

&#x20;Since set is an unordered data type, there is no way of determining which item will be popped. It is completely arbitrary.&#x20;

We can also remove all the items from a set using the clear() method.

{% tabs %}
{% tab title="Python" %}

```python
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)

# pop an element
# Output: random element
print(my_set.pop())

# pop another element
my_set.pop()
print(my_set)

# clear my_set
# Output: set()
my_set.clear()
print(my_set)

print(my_set)

```

{% endtab %}

{% tab title="Output" %}

```
{'H', 'l', 'r', 'W', 'o', 'd', 'e'}
H
{'r', 'W', 'o', 'd', 'e'}
set()

```

{% endtab %}
{% endtabs %}

### Python Set Operations&#x20;

Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods.

&#x20;Let us consider the following two sets for the following operations.\\

```python
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}

```

### **Set Union**

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQV40j9cl6aao5VJPb%2F-MjQayvGA43-LrevDWQW%2FSchermafbeelding%202021-09-12%20220342.jpeg?alt=media\&token=0d31cfe6-d77c-4d98-8df3-7530877b3956)

Union of A and B is a set of all elements from both sets.&#x20;

Union is performed using | operator. Same can be accomplished using the union() method.

{% tabs %}
{% tab title="Python" %}

```python
# Set union method
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)

```

{% endtab %}

{% tab title="Output" %}

```
{1, 2, 3, 4, 5, 6, 7, 8}

```

{% endtab %}
{% endtabs %}

**Try the following examples on Python shell.**

```python
# use union function
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}

# use union function on B
>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}

```

### **Set Intersection**

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQV40j9cl6aao5VJPb%2F-MjQbV4VuePzkkIUKwbi%2FSchermafbeelding%202021-09-12%20220600.jpeg?alt=media\&token=222db541-01c5-48c0-a35a-d4d53e4392c8)

Intersection of A and B is a set of elements that are common in both the sets.

Intersection is performed using & operator. Same can be accomplished using the intersection() metho&#x64;**.**

\\

{% tabs %}
{% tab title="Python" %}

```python
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use & operator
# Output: {4, 5}
print(A & B)

```

{% endtab %}

{% tab title="Output" %}

```
{4, 5}

```

{% endtab %}
{% endtabs %}

Try the following examples on Python shell.

```python
# use intersection function on A
>>> A.intersection(B)
{4, 5}

# use intersection function on B
>>> B.intersection(A)
{4, 5}

```

### Set Difference

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQcOklm8dvWzMtRq_x%2F-MjQc_q-QwGM7YyGJEzb%2FSchermafbeelding%202021-09-12%20221046.jpeg?alt=media\&token=53e349b2-6a96-40d8-b230-9d85da0fc4a6)

Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of elements in B but not in A.

Difference is performed using - operator. Same can be accomplished using the difference() method

{% tabs %}
{% tab title="Python" %}

```python
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use - operator on A
# Output: {1, 2, 3}
print(A - B)

```

{% endtab %}

{% tab title="Output" %}

```
{1, 2, 3}

```

{% endtab %}
{% endtabs %}

Try the following examples on Python shell

```python
# use difference function on A
>>> A.difference(B)
{1, 2, 3}

# use - operator on B
>>> B - A
{8, 6, 7}

# use difference function on B
>>> B.difference(A)
{8, 6, 7}

```

### **Set Symmetric Difference**

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQd3P9MLq_bXRAjpcc%2F-MjTgzHMcAqd252AnKY9%2FSchermafbeelding%202021-09-13%20122851.jpeg?alt=media\&token=28396b73-4239-4da9-9a04-892afdc4cd9e)

Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding the intersection).&#x20;

Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric\_difference() .

{% tabs %}
{% tab title="Python" %}

```python
# Symmetric difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)

```

{% endtab %}

{% tab title="Output" %}

```
{1, 2, 3, 6, 7, 8}

```

{% endtab %}
{% endtabs %}

Try the following examples on Python shell.

```python
# use symmetric_difference function on A
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}

# use symmetric_difference function on B
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}

```

### Other Python Set Methods&#x20;

There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with the set objects:

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQd3P9MLq_bXRAjpcc%2F-MjTi77OvBjyLiMim4lq%2FSchermafbeelding%202021-09-13%20123217.jpeg?alt=media\&token=14fed82f-e693-43b2-a7ff-a508849ede02)

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQd3P9MLq_bXRAjpcc%2F-MjTi9lZwyxDEMsqS0BE%2FSchermafbeelding%202021-09-13%20123242.jpeg?alt=media\&token=09a6e315-394b-4b61-99a7-e83ecc50bd27)

### **Other Set Operations**

#### **Set Membership Test**

We can test if an item exists in a set or not, using the in keyword

{% tabs %}
{% tab title="Python" %}

```python
# in keyword in a set
# initialize my_set
my_set = set("apple")

# check if 'a' is present
# Output: True
print('a' in my_set)

# check if 'p' is present
# Output: False
print('p' not in my_set)

```

{% endtab %}

{% tab title="Output" %}

```
True
False

```

{% endtab %}
{% endtabs %}

#### **Iterating Through a Set**

We can iterate through each item in a set using a for loo&#x70;**.**\\

```python
>>> for letter in set("apple"):
...    print(letter)
...   
a
p
e
l

```

#### **Built-in Functions with Set**

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with sets to perform different tasks.\\

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQd3P9MLq_bXRAjpcc%2F-MjTj8p6Y_IDGSKoyX_t%2FSchermafbeelding%202021-09-13%20123753.jpeg?alt=media\&token=430ca2f1-af8c-4362-affe-fe20e2a0f09b)

### **Python Frozenset**

Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozensets are immutable sets.

Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand, frozensets are hashable and can be used as keys to a dictionary.

Frozensets can be created using the [frozenset()](https://www.programiz.com/python-programming/methods/built-in/frozenset) function.

This data type supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric\_difference() and union(). Being immutable, it does not have methods that add or remove elements.\\

```python
# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
```

Try these examples on Python shell.\\

```python
>>> A.isdisjoint(B)
False
>>> A.difference(B)
frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})
>>> A.add(3)
...
AttributeError: 'frozenset' object has no attribute 'add'

```

## Dictionary in Python

{% embed url="<https://www.youtube.com/watch?v=daefaLgNkw0>" %}

In this tutorial, you'll learn everything about Python dictionaries; how they are created, accessing, adding, removing elements from them and various built-in methods.

&#x20;Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair.&#x20;

Dictionaries are optimized to retrieve values when the key is known.

### &#x20;Creating Python Dictionary&#x20;

Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.

An item has a key and a corresponding value that is expressed as a pair ( key: value ).&#x20;

While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique

```python
# empty dictionary
my_dict = {}

# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])

```

As you can see from above, we can also create a dictionary using the built-in dict() function.

### Accessing Elements from Dictionary&#x20;

While indexing is used with other data types to access values, a dictionary uses keys . Keys can be used either inside square brackets \[] or with the get() method.&#x20;

If we use the square brackets \[] , KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.

{% tabs %}
{% tab title="Python" %}

```python
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error
# Output None
print(my_dict.get('address'))

# KeyError
print(my_dict['address'])

```

{% endtab %}

{% tab title="Output" %}

```
Jack
26
None
Traceback (most recent call last):
  File "<string>", line 15, in <module>
    print(my_dict['address'])
KeyError: 'address'

```

{% endtab %}
{% endtabs %}

### Changing and Adding Dictionary elements&#x20;

Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.

&#x20;If the key is already present, then the existing value gets updated. In case the key is not present, a new ( key: value ) pair is added to the dictionary.

{% tabs %}
{% tab title="Python" %}

```python
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}

# update value
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
```

{% endtab %}

{% tab title="Output" %}

```
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

```

{% endtab %}
{% endtabs %}

### Removing elements from Dictionary

&#x20;We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value .&#x20;

The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All the items can be removed at once, using the clear() method.&#x20;

We can also use the del keyword to remove individual items or the entire dictionary itself.

{% tabs %}
{% tab title="Python" %}

```python
# Removing elements from a dictionary

# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)

# remove an arbitrary item, return (key,value)
# Output: (5, 25)
print(squares.popitem())

# Output: {1: 1, 2: 4, 3: 9}
print(squares)

# remove all items
squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself
del squares

# Throws Error
print(squares)

```

{% endtab %}

{% tab title="Output" %}

```
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
Traceback (most recent call last):
  File "<string>", line 30, in <module>
    print(squares)
NameError: name 'squares' is not defined

```

{% endtab %}
{% endtabs %}

### Python Dictionary Methods&#x20;

Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQd3P9MLq_bXRAjpcc%2F-MjTl0R7KbcvWSfrbAzp%2FSchermafbeelding%202021-09-13%20124556.jpeg?alt=media\&token=8c89fa53-5492-4398-aba7-d1fc00d6ecea)

Here are a few example use cases of these methods.\\

{% tabs %}
{% tab title="Python" %}

```python
# Dictionary Methods
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)

# Output: {'English': 0, 'Math': 0, 'Science': 0}
print(marks)

for item in marks.items():
    print(item)

# Output: ['English', 'Math', 'Science']
print(list(sorted(marks.keys())))

```

{% endtab %}

{% tab title="Output" %}

```
{'Math': 0, 'English': 0, 'Science': 0}
('Math', 0)
('English', 0)
('Science', 0)
['English', 'Math', 'Science']

```

{% endtab %}
{% endtabs %}

### **Python Dictionary Comprehension**

Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.

Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly braces {}.

Here is an example to make a dictionary with each item being a pair of a number and its square.\\

{% tabs %}
{% tab title="Python" %}

```python
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}

print(squares)

```

{% endtab %}

{% tab title="Output" %}

```
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

```

{% endtab %}
{% endtabs %}

This code is equivalent to\\

{% tabs %}
{% tab title="Python" %}

```python
squares = {}
for x in range(6):
    squares[x] = x*x
print(squares)

```

{% endtab %}

{% tab title="Output" %}

```
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

```

{% endtab %}
{% endtabs %}

A dictionary comprehension can optionally contain more [for](https://www.programiz.com/python-programming/for-loop) or [if](https://www.programiz.com/python-programming/if-elif-else) statements.

An optional if statement can filter out items to form the new dictionary.

Here are some examples to make a dictionary with only odd items.\\

{% tabs %}
{% tab title="Python" %}

```python
# Dictionary Comprehension with if conditional
odd_squares = {x: x*x for x in range(11) if x % 2 == 1}

print(odd_squares)

```

{% endtab %}

{% tab title="Output" %}

```
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**To learn more dictionary comprehensions, visit** [**Python Dictionary Comprehension**](https://www.programiz.com/python-programming/dictionary-comprehension)**.**\\

{% endhint %}

### **Other Dictionary Operations**

#### Dictionary Membership Test

We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for the keys and not for the values.\\

{% tabs %}
{% tab title="Python" %}

```python
# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# Output: True
print(1 in squares)

# Output: True
print(2 not in squares)

# membership tests for key only not value
# Output: False
print(49 in squares)

```

{% endtab %}

{% tab title="Output" %}

```
True
True
False

```

{% endtab %}
{% endtabs %}

#### **Iterating Through a Dictionary**

We can iterate through each key in a dictionary using a for loop.\\

{% tabs %}
{% tab title="Python" %}

```python
# Iterating through a Dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
    print(squares[i])

```

{% endtab %}

{% tab title="Output" %}

```
1
9
25
49
81

```

{% endtab %}
{% endtabs %}

#### **Dictionary Built-in Functions**

Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform different tasks.

![](https://2843449504-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXS9gjR6N_CAer7Mflk%2F-MjQd3P9MLq_bXRAjpcc%2F-MjTmnpbi-uzO7MycUf7%2FSchermafbeelding%202021-09-13%20125414.jpeg?alt=media\&token=713a8378-7258-40c4-a509-a66e6fb3f952)

Here are some examples that use built-in functions to work with a dictionary.\\

{% tabs %}
{% tab title="Python" %}

```python
# Dictionary Built-in Functions
squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# Output: False
print(all(squares))

# Output: True
print(any(squares))

# Output: 6
print(len(squares))

# Output: [0, 1, 3, 5, 7, 9]
print(sorted(squares))

```

{% endtab %}

{% tab title="Output" %}

```
False
True
6
[0, 1, 3, 5, 7, 9]

```

{% endtab %}
{% endtabs %}

&#x20;                                                **END OF THE LECTURE**
