3

I was wondering if it is possible to run an enumerate loop as as we can see below

int_term = [scipy.quad(t_x,x0,i)[0] for i in enumerate(x_vals)]

or do we have to write it this way

for i in enumerate(x_vals)
3
  • Both ways are exactly the same. Just one is more compacted Commented May 27, 2021 at 21:20
  • enumerate isn't a loop at all. It's a iterable type that provides "annotated" elements from another iterable. You can iterate over it using whatever technique you would dive use to iterate over the original. Commented May 27, 2021 at 21:27
  • Keep in mind that quad expects that the args parameter be a tuple. i from enumerate will be tuple, but it might not be what your t_x expects. During testing, I suggest including a print at the start of t_x to display or otherwise tell you what the arguments are. Commented May 27, 2021 at 22:18

1 Answer 1

4

Hopefully this clarifies what exactly enumerate does:

>>> list(enumerate('abc'))
[(0, 'a'), (1, 'b'), (2, 'c')]

It just turns your list into a list of a pairs where each of your elements is joined with the index i.e. a with 0, b with 1 and c with 2.

That's not exactly true because it is an iterator rather than an actual list - so it provides you with values lazily when you wrap another iterator.

Looping over it is therefore the same as any other lists except usually it is done the following way:

for i, x in enumerate(xs)

You could still use:

for i in enumerate(xs)

but then just know that i is going to be a tuple with some int, and some object from xs.

Sign up to request clarification or add additional context in comments.

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.