Python Code Example: even numbers in a list

The code is checking for even numbers in the list “myList”.
Here is the code explanation:

  1. A list named “myList” is created with some integer values.
  2. The variable “length” is assigned the length of the list “myList”.
  3. A for loop is used to iterate over the elements of “myList”. The for loop uses the “range” function to loop over the index values from 0 to “length-1”.
  4. Inside the for loop, an if statement checks if the current element of the list is even. The modulo operator (%) is used to check this. If the element is even, the if statement is executed.
  5. Within the if statement, the element is cast to a string and printed, followed by a space. The “end” parameter of the print function is set to a space to separate each even number with a space.

In this way, the code checks for even numbers in the list “myList” and prints them out, separated by spaces.

myList = [12, 44, 55, 66, 77, 4, 5, 6, 7]
length = len(myList)

for i in range(0, length):
    if myList[i] % 2 == 0:
        print(str(myList[i]), end=' ')
Output
12 44 66 4 6