We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Not wrong, but you have not used list comprehension. Consider a list called 'a' with even and odd numbers. Now suppose you want to create a list 'b' that contains only the even numbers of list 'a'.
One way to do this in the usual way with a loop:
b = []
for n in a:
if n % 2 == 0:
b.append(n)
Using list comprehension this would look like this single line:
b = [n for n in a if n % 2 == 0]
The challenge in this problem is creating nested list comprehesions, which can be tricky. See PEP 202.
(Sorry for the broken formatting, but it's not possible to code-format in replies here in HR.)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
List Comprehensions
You are viewing a single comment's thread. Return to all comments →
Not wrong, but you have not used list comprehension. Consider a list called 'a' with even and odd numbers. Now suppose you want to create a list 'b' that contains only the even numbers of list 'a'.
One way to do this in the usual way with a loop:
Using list comprehension this would look like this single line:
The challenge in this problem is creating nested list comprehesions, which can be tricky. See PEP 202.
(Sorry for the broken formatting, but it's not possible to code-format in replies here in HR.)