1

NON-HOMEWORK

I have list of floats x, and I want to turn it into list y, a list of all the tenth elements in x.

For my own reasons, I really want to do this in a tiny amount of lines. I came up with something like this:

i = 0
y = filter(lambda x: (++i)%10; x)

Theoretically this should work, i is already defined, and the ++i would typically add one to variable i, then go about the expression.

Unfortunately, ++ doesn't exist in Python.

Any Pythonic ways to go about this?

Another idea I had was to use a map, and have the expression push elements onto list y.

Let me know if I can be more clear.

0

3 Answers 3

15

Use Extended slices:

>>> x = range(1,101)
>>> y = x[9::10] # 9 -> start from 10th, 10: step
>>> y
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful. Hadn't seen this before, as, though I've been using Python for a while, I haven't fully explored a lot of the more Pythonic ways of doing things. Thanks!
3

What about [value for index, value in enumerate(list_of_floats) if index % 10 == 0]?

1 Comment

It's worth noting that slicing is better in this case. However, this technique is worth knowing in cases where the filtering criterion is more complex.
0

Alternative that use itertools.count:

>>> x = range(1, 101)
>>> i = itertools.count(1)
>>> y = filter(lambda item: next(i) % 10 == 0, x)
>>> y
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.