List Operations | Using PYTHON

Problem : Write functions to:

🔰Reverse a list of elements.
🔰Find the Sum of all elements in a list.
🔰Check if a given elements exists in a list.

Solution:👇


    How the Program Works :

Step 1: Define Functions:

👉The code defines three separate functions:

reverse_list(my_list): This function takes a list (my_list) as input and returns a new list with the elements in reverse order.

sum_list(my_list): This function takes a list (my_list) as input and returns the sum of all the elements in the list.

 ♦element_exists(my_list, element): This function takes two arguments: a list (my_list) and an element (element). It checks if the given element exists within the my_list and returns True if found, False otherwise.

Steps 2: List Slicing (Reverse Function):

👉The reverse_list function utilizes Python's powerful list slicing syntax for efficient reversal. Here's how it works: 

my_list[::-1]: This expression creates a slice of the original list (my_list). 

🔷The empty : in the middle indicates the entire list is being sliced. 

🔷-1 specifies taking elements in reverse order (from the end to the beginning).

Step 3: sum() function (Sum Function):

👉The sum_list function employs the built-in sum() function in Python. It takes an iterable (like a list) as input and returns the sum of all its elements.

Sstep 4: in Operator (Element Exists Function):

👉The element_exists function leverages the in operator in Python. The expression element in my_list evaluates to True if the element is found within the my_list, and False if not.

Step 5: Example Usage:

The code snippet demonstrates how to use these functions with an example list my_list = [1, 2, 3, 4, 5]:

    • print(reverse_list(my_list)): Reverses the list and prints [5, 4, 3, 2, 1].
    • print(sum_list(my_list)): Calculates the sum and prints 15.
    • print(element_exists(my_list, 3)): Checks for element 3 and prints True.


1 Comments

Previous Post Next Post

Popular Items