Given a list of N numbers, use a single list comprehension to produce a new list that only contains those values that are: (a) even numbers, and (b) from elements in the original list that had even indices .

A simple solution to this problem would be as follows [x for x in list[::2] if x%2 == 0] For example, given the following list: list = [ 1 , 3 , 5 , 8 , 10 , 13 , 18 , 36 , 78 ] The list comprehension [x for x in list[::2] if x%2 == 0] will evaluate to: [10, 18, 78] The expression works by first taking the numbers that are at the even indices, and then filtering out all the odd numbers.

WA
Answered by Waseem A. Python tutor

2651 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

How would you get a piece of code to print the numbers 1 to 10


h


How can you take a list of numbers and add 3 to every number in the list using only one line of code?


Ask the user for a number and output the smallest divisor, bigger than one, for the inputted number. Output "Prime" if the number is a prime number.


We're here to help

contact us iconContact ustelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences