sourcery icon indicating copy to clipboard operation
sourcery copied to clipboard

Extending `list-comprehension` for `zip-for-loops`

Open Anselmoo opened this issue 3 years ago • 0 comments

Checklist

  • [x] I think this refactoring is useful for everyone (if it's too specific, consider a custom rule)
  • [x] I have checked there are no similar issues suggesting the same thing

Description

Extending the list-comprehension for zip-for-loops. Currently, only merge-list-appends-into-extend is applied, but there might be cases where a double-for-loop / pydantic will be more elegant.

Code Before

_list = []

for i,j in zip(range(10), range(10)[::-1]):
    _list.append(i)
    _list.append(j)
print(_list)

will sourcery currently refactor like this:

_list = []

for i,j in zip(range(10), range(10)[::-1]):
    _list.extend((i, j))
print(_list)
[0, 9, 1, 8, 2, 7, 3, 6, 4, 5, 5, 4, 6, 3, 7, 2, 8, 1, 9, 0]

Code After

However, this can also be achieved as a one-liner

_list = [i for j in zip(range(10), range(10)[::-1]) for i in j]
print(_list)
[0, 9, 1, 8, 2, 7, 3, 6, 4, 5, 5, 4, 6, 3, 7, 2, 8, 1, 9, 0]

Anselmoo avatar Nov 06 '22 15:11 Anselmoo