 How to print the even array numbers only in a list? | Sololearn: Learn to code for FREE!

0

# How to print the even array numbers only in a list?

My_list =[array[1, 2 ,3], array[4,5,6], array[8,9,10], array[11,12,13], array[0,5,66], array[9,19,21]] I want my output to be the following: array[4,5,6] array[11,12,13] array[9,19,21]

+5

for i in range(len(My_list)) : if i%2!=0: print(My_list[i])

+4

for the sake of correctness: (1) the code as mentioned in the initial post does not work. to use the python "array" class, the module "array" has to be imported. (BTW - i can not remember that i have seen codes here using the "array" class in python. it has a limited set ot methods compared to the "list" class, and if speed matters i would prefer to use numpy) (2) to create an array the syntax has to be: My_list = [array('i',[1,2,3]), array(.....)], in which 'i' indicates the data type of the array to be created to access the list of arrays, a for loop can be used as mentioned by Abhay, also indexing and slicing is possible (3) i assume that the creator of the post wanted to print out all arrays at an even index position. as 0 is the first index, and it is an even number, the output should be a bit different

+3

Use the boolean comparison ((int)arr[i]%2==0), if true print number else continue...works in all languages

+2

Just iterate over the list and test the value, if it's even print it otherwise don't print it.

+2

+2

Just to be pedantic those are the odd number entries not the even number ones, as demonstrated by Abhey's code. In Python index numbers start from zero so you are printing the lists/arrays at index numbers 1, 3, and 5. Since modulo arithmetic uses division it is computationally more expensive that a bitwise operation. A speed improvement can be achieved using if i & 1: or if you prefer... if i & 1 == 1: for the even numbered elements use.. if i & 1 == 0:

+2

Karzan Here's a possible solution: for i in range(1, len(My_list), 2): print(My_list[i]) # Hope this helps

+2

Calvin Thomas and others. Yes, thank you guys for helping. Your suggestions was valuable to solve my problem.

+1

Karzan, disregard my previous reply. I thought that you wanted the even values within the list. My apologies.

0

Martin Taylor can you share an example please?

0

RKK your code prints everything in the list. That is not what I am looking for.

0

RKK I am running on my PC. How can I share what I am seeing? Can I share photos here?