---
# System prepended metadata

title: COHORT III WEEK 8

---

<strong>DAY 1</strong>

<strong>TUPLE</strong>

A tuple is a collection similar to a Python list. The primary difference is that we cannot modify a tuple once it is created.

We create a tuple by placing items inside parentheses (). 
        
    For example,

    numbers = (1, 2, -5)
    print(numbers)

    Output: (1, 2, -5)
    
Create a Tuple Using tuple() Constructor method

We can also create a tuple using a tuple() constructor. 
    
    For example,

    name = tuple(('Jack', 'Maria', 'David'))
    print(name)

    Output: ('Jack', 'Maria', 'David')
    
Different Types of Python Tuples
Here are the different types of tuples we can create in Python.

Empty Tuple

    create an empty tuple
    
    empty_tuple = ()
    print(empty_tuple)

    Output: ()
    
Tuple of different data types

    tuple of string types
    names = ('James', 'Jack', 'Eva')
    print (names)

    tuple of float types
    float_values = (1.2, 3.4, 2.1)
    print(float_values)
    
Tuple of mixed data types

    tuple including string and integer
    mixed_tuple = (2, 'Hello', 'Python')
    print(mixed_tuple)

    Output: (2, 'Hello', 'Python')
    
CHARACTERISTICS OF TUPLE

Tuples are:

Ordered - They maintain the order of elements.
Immutable - They cannot be changed after creation.
Allow duplicates - They can contain duplicate values.

ACCESS TUPLE ITEMS

Each item in a tuple is associated with a number, known as a index.

The index always starts from 0, meaning the first item of a tuple is at index 0, the second item is at index 1, and so on.

    name = ('John', 'Peter', 'James')
    inex =    0        1        2
    
We use index numbers to access tuple items. For example,

    languages = ('Python', 'Swift', 'C++')

    access the first item
    print(languages[0])   # Python

    access the third item
    print(languages[2])   # C++
    
Tuple Cannot be Modified

Python tuples are immutable (unchangeable). We cannot add, change, or delete items of a tuple.

If we try to modify a tuple, we will get an error.

    For example,

    cars = ('BMW', 'Tesla', 'Ford', 'Toyota')

    trying to modify a tuple
    cars[0] = 'Nissan'    # error
       
    print(cars)

PYTHON TUPLE LENGTH
We use the len() function to find the number of items present in a tuple.

    For example,

    cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
    print('Total Items:', len(cars)) 
       
    Output: Total Items: 4

    # Output
    apple
    banana
    orange

Check if an Item Exists in the Tuple

We use the in keyword to check if an item exists in the tuple.

    For example,

    colors = ('red', 'orange', 'blue')
    
    print('yellow' in colors)    # False
    print('red' in colors)       # True
    
Change Tuple Items

Python Tuples are immutable - we cannot change the items of a tuple once created.

If we try to do so, we will get an error.

    For example,

    fruits = ('apple', 'cherry', 'orange')

    trying to change the second item to 'banana'
    fruits[1] = 'banana'

    print(fruits) 

    Output: TypeError: 'tuple' object does not support item assignment
    
Delete Tuples

We cannot delete individual items of a tuple. However, we can delete the tuple itself using the del statement.

    For example,

    animals = ('dog', 'cat', 'rat')

    deleting the tuple
    del animals

    Here, we have deleted the animals tuple.
    
Create a Python Tuple With One Item

When we want to create a tuple with a single item, we might do the following:

    var = ('Hello')
    print(var)  # string

But this would not create a tuple; instead, it would be considered a string.

To solve this, we need to include a trailing comma after the item.

    For example,

    var = ('Hello',) 
    print(var)  # tuple

    Output: ('Hello',)

<strong>DAY 2</strong>

<strong>SET</strong>

A set is a collection of unique data, meaning that elements within a set cannot be duplicated.

For instance, if we need to store information about student IDs, a set is suitable since student IDs cannot have duplicates.

Create a Set in Python
In Python, we create sets by placing all the elements inside curly braces {}, separated by commas.

A set 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, sets or dictionaries as its elements.

Let's see an example,

create a set of integer type
    
    student_id = {112, 114, 116, 118, 115}
    print('Student ID:', student_id)
    
    Output

    Student ID: {112, 114, 115, 116, 118}

create a set of string type

    vowel_letters = {'a', 'e', 'i', 'o', 'u'}
    print('Vowel Letters:', vowel_letters)
    
    Output
    
    Vowel Letters: {'u', 'a', 'e', 'i', 'o'}

create a set of mixed data types

    mixed_set = {'Hello', 101, -2, 'Bye'}
    print('Set of mixed data types:', mixed_set)

    Output
    
    Set of mixed data types: {'Hello', 'Bye', 101, -2}

In the above examples, we have created different types of sets by placing all the elements inside the curly braces {}.

Note: When you run this code, you might get output in a different order. This is because the set has no particular order.





Create an Empty Set in Python

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.

    For example,

    # create an empty set
    empty_set = set()

    # check data type of empty_set
    print('Data type of empty_set:', type(empty_set))
    
    # Output
    Data type of empty_set: <class 'set'>
    
    # create an empty dictionary
    empty_dictionary = { }

    # check data type of dictionary_set
    print('Data type of empty_dictionary:',type(empty_dictionary))

    # Output
    Data type of empty_dictionary: <class 'dict'>
    
Here,

empty_set - an empty set created using set()
empty_dictionary - an empty dictionary created using

Finally, we have used the type() function to know which class empty_set and empty_dictionary belong to.

Duplicate Items in a Set
Let's see what will happen if we try to include duplicate items in a set.

    numbers = {2, 4, 6, 6, 2, 8}
    print(numbers)   
    
    #  Output
    {8, 2, 4, 6}

Here, we can see there are no duplicate items in the set as a set cannot contain duplicates.

Add and Update Set Items in Python
Sets are mutable. However, since they are unordered, indexing has no meaning.

We cannot access or change an element of a set using indexing or slicing. The set data type does not support it.

Add Items to a Set in Python
In Python, we use the add() method to add an item to a set.

    For example,

    numbers = {21, 34, 54, 12}

    print('Initial Set:',numbers)
    
    # Output
    Initial Set: {34, 12, 21, 54}

    using add() method
    numbers.add(32)

    print('Updated Set:', numbers) 

    # Output
    Updated Set: {32, 34, 12, 21, 54}


In the above example, we have created a set named numbers. Notice the line,

    numbers.add(32)
    Here, add() adds 32 to our set.

Update Python Set

The update() method is used to update the set with items other collection types (lists, tuples, sets, etc).

    For example,

    companies = {'Lacoste', 'Ralph Lauren'}
    tech_companies = ['apple', 'google', 'apple']

    # using update() method
    
    companies.update(tech_companies)

    print(companies)

    # Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}

Here, all the unique elements of tech_companies are added to the companies set.

Remove an Element from a Set

We use the discard() method to remove the specified element from a set.

    For example,

    languages = {'Swift', 'Java', 'Python'}

    print('Initial Set:',languages)
    
    # Output
    Initial Set: {'Python', 'Swift', 'Java'}

    #remove 'Java' from a set
    
    removedValue = languages.discard('Java')

    print('Set after remove():', languages)

    # Output
    Set after remove(): {'Python', 'Swift'}
    
Here, we have used the discard() method to remove 'Java' from the languages set.


<strong>DAY 3</strong>

<strong>PYTHON DICTIONARY</strong>

A Python dictionary is a collection of items, similar to lists and tuples. However, unlike lists and tuples, each item in a dictionary is a key-value pair (consisting of a key and a value).

Create a Dictionary
We create a dictionary by placing key: value pairs inside curly brackets {}, separated by commas.

    For example,

    #creating a dictionary
    
    country_capitals = {
      "Germany": "Berlin", 
      "Canada": "Ottawa", 
      "England": "London"
    }

    #printing the dictionary
    print(country_capitals)

    #Output

    {'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}
    
The country_capitals dictionary has three elements (key-value pairs), where 'Germany' is the key and 'Berlin' is the value assigned to it and so on.
    
    country_capitals = {
      "Germany": "Berlin", ----- element 1
      "Canada": "Ottawa", ------ element 2
      "England": "London" ------ element 3
    }    
         key   :  value
         
         
Notes:

Dictionary keys must be immutable, such as tuples, strings, integers, etc. We cannot use mutable (changeable) objects such as lists as keys.

<strong>VALID AND INVALID DICTIONARIES</strong>

KEYS OF A DICTIONARY MUST BE IMMUTABLE

Immutable objects can't be changed once created. Some immutable objects in Python are integer, tuple and string.

    # valid dictionary
    # integer as a key
    my_dict = {1: "one", 2: "two", 3: "three"}

    # valid dictionary
    # tuple as a key
    my_dict = {(1, 2): "one two", 3: "three"}

    # invalid dictionary
    # Error: using a list as a key is not allowed
    my_dict = {1: "Hello", [1, 2]: "Hello Hi"}

    # valid dictionary
    # string as a key, list as a value
    my_dict = {"USA": ["Chicago", "California", "New York"]}

In this example, we have used integers, tuples, and strings as keys for the dictionaries. When we used a list as a key, an error message occurred due to the list's mutable nature.

Note: Dictionary values can be of any data type, including mutable types like lists.

KEYS OF A DICTIONARY MUST BE UNIQUE

The keys of a dictionary must be unique. If there are duplicate keys, the later value of the key overwrites the previous value.

    houses = {
        "Harry Potter": "Gryffindor",
        "Hermione Granger": "Gryffindor",
        "Ron Weasley": "Gryffindor",
        # duplicate key with a different house
        "Harry Potter": "Slytherin"
    }

    print(houses)
    
    #Output

    {'Harry Potter': 'Slytherin', 'Hermione Granger': 'Gryffindor', 
    'Ron Weasley': 'Gryffindor'}
    
Here, the key Harry Potter is first assigned to Gryffindor. However, there is a second entry where Harry Potter is assigned to Slytherin.

As duplicate keys are not allowed in a dictionary, the last entry Slytherin overwrites the previous value Gryffindor.

Access Dictionary Items

We can access the value of a dictionary item by placing the key inside square brackets.

    country_capitals = {
      "Germany": "Berlin", 
      "Canada": "Ottawa", 
      "England": "London"
    }

    # access the value of keys
    print(country_capitals["Germany"])    # Output: Berlin
    print(country_capitals["England"])    # Output: London

    Note: We can also use the get() method to access dictionary items.




