Explore Lists and Loops in Python

In Python, a list is a versatile data structure used to store collections of items. Lists are mutable, meaning you can modify, add, or remove elements from them after creation. Lists are denoted by square brackets [] and elements inside a list are separated by commas.

Common List Operations:

Examples of Looping Through a List:

Using a While Loop:

        numbers = [1, 2, 3, 4, 5]
        i = 0
        while i < len(numbers):
            print(numbers[i])
            i += 1
    

Using a For Loop:

        numbers = [1, 2, 3, 4, 5]
        for num in numbers:
            print(num)
    

Instructions:

To work on the exercises, you can write Python code in your favorite text editor or IDE (Integrated Development Environment). Save the code in a .py file and run it using the Python interpreter. Observe the outputs and verify that the results match the expected outputs mentioned in each exercise.

Exercises:

  1. Sum of Elements:
                    Input: [1, 2, 3, 4, 5]
                    Output: 15
                
  2. Finding Maximum and Minimum:
                    Input: [10, 5, 25, 8, 20]
                    Output: Maximum: 25, Minimum: 5
                
  3. Square All Elements:
                    Input: [1, 2, 3, 4, 5]
                    Output: [1, 4, 9, 16, 25]
                
  4. Remove Duplicates:
                    Input: [1, 2, 2, 3, 4, 4, 5]
                    Output: [1, 2, 3, 4, 5]
                
  5. List Comprehension - Even Numbers:
                    Input: [1, 2, 3, 4, 5, 6]
                    Output: [2, 4, 6]
                
  6. Reverse List:
                    Input: [1, 2, 3, 4, 5]
                    Output: [5, 4, 3, 2, 1]
                
  7. Count Occurrences:
                    Input: [1, 2, 2, 3, 4, 4, 5], Element: 2
                    Output: 2
                
  8. Join Lists:
                    Input: [1, 2, 3], [4, 5, 6]
                    Output: [1, 2, 3, 4, 5, 6]
                

How to Loop over Lists in Python YouTube Video