Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Complicated variable assignment in for loops #23

Closed
MitalAshok opened this issue Sep 2, 2017 · 2 comments
Closed

Feature request: Complicated variable assignment in for loops #23

MitalAshok opened this issue Sep 2, 2017 · 2 comments
Assignees

Comments

@MitalAshok
Copy link

Normally in a for loop, you just do for <variable_name> in iterable:, but you can also do use anything that is a valid assignment target (An "lvalue" in C). Like for f()(g)[t].x in seq: is perfectly valid syntax.

Here is a draft:


For what?

d = {}
for d['n'] in range(5):
    print(d)

Output:

{'n': 0}
{'n': 1}
{'n': 2}
{'n': 3}
{'n': 4}
def indexed_dict(seq):
    d = {}
    for i, d[i] in enumerate(seq):
        pass
    return d

Output:

>>> indexed_dict(['a', 'b', 'c', 'd'])
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}
>>> indexed_dict('foobar')
{0: 'f', 1: 'o', 2: 'o', 3: 'b', 4: 'a', 5: 'r'}

💡 Explanation:

  • A for statement is defined in the Python grammar as:

    for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
    

    Where exprlist is the assignment target. This means that the equivalent of {exprlist} = {next_value} is executed for each item in the iterable.

  • Normally, this is a single variable. For example, with for i in iterator:, the equivalent of i = next(iterator) is executed before every time the block after for is.

  • d['n'] = value sets the 'n' key to the given value, so the 'n' key is assigned to a value in the range each time, and printed.

  • The function uses enumerate() to generate a new value for i each time (A counter going up). It then sets the (just assigned) i key of the dictionary. For example, in the first example, unrolling the loop looks like:

    i, d[i] = (0, 'a')
    pass
    i, d[i] = (1, 'b')
    pass
    i, d[i] = (2, 'c')
    pass
    i, d[i] = (3, 'd')
    pass
@satwikkansal satwikkansal self-assigned this Sep 4, 2017
@satwikkansal
Copy link
Owner

Hey @MitalAshok Thanks for this cool suggestion. I've added your example in 753d0b6 . For brevity of the overall contents of the collection, I had to skip some of the content.

If you think it's missing something, or something is incorrect, feel free to reopen the issue.
Cheers!

@lzblack
Copy link

lzblack commented Oct 30, 2017

Great point!

The second example should work same as dictionary comprehension:

some_string = "wtf"
some_dict = {i: letter for i, letter in enumerate(some_string)}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants