How to count a number of even integers in a nested list
What is a nested list?
A nested list is a list whose elements are lists:
Example
Let l be the list and l1, l2, and l3 be the sub lists:
l1 = [1,2,3]
l2 = [4,5,6]
l3 = [7,8,9]
l = [[1,2,3],[4,5,6],[7,8,9]]
Code
l = [[1,2,8], [3,5,5], [4,6,6]]count=0for i in l:for j in i:if(j%2==0):count=count+1print(count)
Explanation
-
A nested list,
l, is taken with sub-lists. -
Count variable is used to count the number of even numbers in the list and is initialized to zero.
-
The nested
forloop is used to access the elements in the list. -
Variable
iis used to access sub-lists in the list, and variablejis used to access elements in sub-listi. -
Th even condition is checked with
jand, if it is satisfied, thecountvalue is incremented by one. -
Finally, the
is printed.count value represents the number of even numbers in a nested list