E
E
enot_style2020-07-12 07:49:51
Python
enot_style, 2020-07-12 07:49:51

How do list generators work?

I started to study generators in Python and a few questions arose:
1. (for input values: 1 2 3 4 5) As I understand it, we take a sequence, in this case, input().split is written to the i variable and converted to int (i) . In this case, I do not understand the work of the variable i . We declare it inside the generator and can access it only after building a list in the form a[i] ? 2. (input values: 1 2 3 4 5) Why in this case the list will be written [1, ' ', 2, ' '....]. As a generator without split() also writes spaces to the list, I assumed that with this form there would be a list of one element i0 = 1 2 3 4 5.
a = [int(i) for i in input().split()]


a = [int(i) for i in input()]

The teacher did not give answers to these questions, because I decided to experiment and did not follow the course assignments, I hope you chew these stupid questions

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-07-12
@enot_style

  1. List comprehensions are an example of a declarative approach, so it's wrong to try to think of them in imperative terms, but a variable ican be thought of as a loop variable that takes on a new iterator value at each iteration. You can't access it after building the list.
  2. Because a string is a sequence of characters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question