how i can solve this | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

how i can solve this

Fill in the blanks to print the first element of the list, if it contains an even number of elements. list = [1, 2, 3, 4] if (list) % 2 == 0 print(list[ ])

17th Nov 2019, 9:28 PM
Mohamede Addar
10 Answers
+ 1
If I'm getting the question right, you want to print the first element if the list contains an even number.. list = [1,2,3,4] Then you just have to iterate through the list for i in list: if i%2==0: print(list[0]) break The break is just there to save time. Since you've gotten what u need, there's no need looping through all elements
20th Nov 2019, 10:30 PM
Isaac Frank
Isaac Frank - avatar
+ 8
Don't forget to to add semi colons ':'
19th Nov 2019, 12:28 PM
Sparshika
Sparshika - avatar
+ 7
#It will only work this way.... list = [1, 2, 3, 4] if len(list) % 2 == 0: print(list[0])
17th Nov 2019, 11:22 PM
ProfOduola🙏🇳🇬
ProfOduola🙏🇳🇬 - avatar
+ 6
Try like this:- list=[1,2,3,4] if len(list)%2==0: print(list[0]) maybe this would help you out 😊
19th Nov 2019, 12:27 PM
Sparshika
Sparshika - avatar
+ 4
list = [1, 2, 3, 4] if len(list) % 2 == 0 print(list[0])
17th Nov 2019, 10:32 PM
rodwynnejones
rodwynnejones - avatar
+ 4
thanks Njeri am also a n00b in python, am kind of treating it like C
18th Nov 2019, 6:42 AM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 2
iterate through the list, and check for an even value if len(list) %2==0 print(list[0])
17th Nov 2019, 9:41 PM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 2
✳AsterisK✳ The question asks to print the first element of the list if the list contains an even number of elements in it, not to print the even numbers in the list. Also you have used i to iterate through the list and also as an index, but indices start at 0, not 1, so your code will check whether the next element in the list is even for a given element rather than the current one. It will produce an IndexError when it gets to 4, since list[4] is the fifth element of the list, which doesn't exist.
18th Nov 2019, 5:47 AM
Njeri
Njeri - avatar
+ 2
✳AsterisK✳ No problem.
18th Nov 2019, 4:12 PM
Njeri
Njeri - avatar
+ 1
Print(list[0])
18th Nov 2019, 5:36 AM
Tipsy
Tipsy - avatar