# How to use list comprehension for code challenge?

a bit confused, how can i use a list comprehension here? don’t think ive done it correctly.

my code so far:

def odd_indices(lst):
new_lst = [lst[i] for i in lst if (i % 2 == 1) and (0 <= i < len(lst))]
return new_lst

I don’t think list comprehension is to blame for anything there. If a regular loop is more comfortable, you might want to do that first while you sort out the logic. At the very least it’s easier to insert print’s to write out what’s being done step by step so that it’s easier to compare to how you would do it manually.

i see, i initially attempted the exercise with a list comprehension, and upon encountering difficulty i did end up using a regular loop, with success. was just curious about how it could be possible with list comprehension. i’ll play around with it and figure it out.
thanks!

They’re not really any different

true, a list comprehension is just a more concise for loop for lists right?

They avoid some boilerplate for a couple common patterns, and because they’re expressions they fit in more places.
Filter and map are also very common operations with some programmers, and comprehensions are often preferred over using filter and map themselves.

``````def add100(x):
return x+100

map(add100, range(3))  # 100 101 102
[x + 100 for x in range(3)]  # 100 101 102
``````

ahh ok, so they’re more useful in certain situations.