Is it possible to add element to that list inside the for?

Asked

Viewed 37 times

-1

In an attempt to make python code smaller, I generated this list in enumerate. The problem is that it does not have a name. How could I add a new element or delete without having the list name to reference?

for index_a, valor in enumerate(list(range(5))):
  • @Max: what is the relation of lambda functions with this case? The person is learning programming and with doubts about the basic use of variables. Even if lambda functions served for something in this case, what does not happen, it would only make sense to cite it in a complete reply detailing very well its use.

1 answer

0

If you need to access a list, put it in a variable.

Direct use of range in a for, with or without enumerate, will create a sequence that will be used only by for.

In case that code would just be:

minha_lista = list(range(5))

for index_a, valor in enumerate(minha_lista):
     ...

And the complete list is available in the variable minha_lista.

Also, the way you were wearing it, it makes no sense convert the range call to a list - you do not need the list, if using the result only in for:

for index_a, valor in enumerate(range(5)):
    ...

(all right that in this case the use of the enumerate is quite superfluous, since the numbers generated by the range will be exactly the same as the indexes generated by the enumerate).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.