Sunday, September 19, 2021

Passing an entire List to a Function

We are going to pass an entire list to a function.

    In [1]: numbers
    Out[1]: [10, 5, 3, 7, 4]

Defining a function which we going to pass the entire list to.  This function multiplies each of the list's element by 2.
    In [2]: def modify_elements(items):
    ...:     for i in range(len(items)):
    ...:         items[i] *= 2
    ...:

    In [3]: modify_elements(numbers)

    In [4]: numbers
    Out[4]: [20, 10, 6, 14, 8]

    In [5]:

Function modify_elemens' items parameter receives a reference to the original list, so the statement in the loop's suite modifies each element in the original list object.

Python built-in Function Enumerate

Using a built-in function Enumerate in Python to access an element's INDEX and VALUE.

Create a list with integers

    In [1]: numbers = [10,5,3,7,4]

    In [2]: type(numbers)
    Out[2]: list

    In [3]:

Apply built-in function Enumerate to numbers

    In [3]: new_numbers = enumerate(numbers)

    In [4]: new_numbers
    Out[4]: <enumerate at 0x233d866db80>

Convert it to list format|

    In [6]: list(new_numbers)
    Out[6]: [(0, 10), (1, 5), (2, 3), (3, 7), (4, 4)]

    In [7]:

Going to create a simple bar chart using the value in numbers

    In [1]: numbers = [10,5,3,7,4]

    In [2]: for index, value in enumerate(numbers):

       ...:     print(f'{index:>8}{value:>8}  {"|" * value}')
       ...:

        0      10  ||||||||||
        1       5  |||||
        2       3  |||
        3       7  |||||||
        4       4  ||||

      In [3]:

Remove duplicate from Python list

 This post is to show how to remove duplicate entries in a List.

Create an empty list and we name it new_list.

In [1]: new_list = []

We iterate a range of integers and assign it to this new_list.

In [2]: for items in range(1,6):
   ...:     new_list += [items]
   ...:

Show what is inside this list

In [3]: new_list
Out[3]: [1, 2, 3, 4, 5]

We iterate another range of integers where there are duplicates into the same new_list

In [4]: for new_items in range(7):
   ...:     new_list += [new_items]
   ...:

This show the new_list has duplicate entries

In [5]: new_list
Out[5]: [1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]

Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.
Then, convert the dictionary back into a list.

In [6]: new_list = list(dict.fromkeys(new_list))

In [7]: new_list
Out[7]: [1, 2, 3, 4, 5, 0, 6]

In [8]: