Can you help me convert this into list comprehension?

Can anyone help me understand how to turn this into a list comprehension? I’m tinkering with the syntax but maybe I haven’t progressed far enough to know the right tool to throw in there.

def delete_starting_evens(lst):
  for i in range(len(lst)):
    if lst[0]%2==0:
      lst.pop(0)
  return lst

It’s been very common to see users modifying the list as they iterate over it. One may question the wisdom of modifying when using a range in a for loop. A while loop is more flexible since it is not affected by changes in length.

My thinking on this problem is to just look for the first odd number in the list.

>>> def remove_starting_evens(x):
	for i, n in enumerate(x):
		if n % 2: return x[i:]
	return []

>>> remove_starting_evens([2, 4, 6, 8, 3, 6, 9, 12])
[3, 6, 9, 12]
>>> remove_starting_evens([2, 4, 6, 8])
[]
>>> remove_starting_evens([])
[]
>>> 
2 Likes

List comprehensions are great. I love using them when it makes sense to do so. Like any tool though, there are times when it is not the best tool for the job.

Ah - haven’t learned enumerate yet. From the documentation, I guess that “i” is the index, and “n” is the value, but you can set the index as a different starting value within the function, i.e. enumerate(x, 1) if you want to start at an index of 1 rather than 0?

For clarity, am I reading it correctly as the following pseudocode?

for index, value in enumerate(x):
if value % 2 returns a value of 0, continue with index+1, otherwise: return x[index:]
otherwise return

Thank you!

1 Like

checks if the modulo is non-zero, meaning odd. That’s the index where we start the slice.

Enumeration is essentially taking a list of values and giving each value an index. Under the hood it is a list of tuples. [(index, value), ...].

The optional second argument is the starting index.

https://book.pythontips.com/en/latest/enumerate.html

I love this iterator since we rarely need to use subscripts.