0

Say I am in the middle of writing series of commands and decide I want to turn it into a for loop. For instance say I have

print('Jane','Bennet')
print('Elizabeth','Bennet')
print('Mary','Bennet')

to start with and I decide I want to turn it into a for loop:

for s in ['Jane','Elizabeth','Mary']:
   print(s,'Bennet')

or possibly even a list comprehension:

[print(s,'Bennet') for s in ['Jane','Elizabeth','Mary']]

Is there a Python IDE that can convert between these forms automatically? Or maybe there are other tools that can do this?

4
  • 1
    As a side not, this list comprehension would build a list of None. You should use comprehensions to build lists, not for the side effects of the functions that get called inside - that is better expressed in normal loops. Commented Dec 8, 2019 at 16:44
  • I’m sure you could find a way to do something like this in most editors, although it might requires scripting/plugins/etc. Is this really that much of a concern? Commented Dec 8, 2019 at 16:53
  • A script or plugin for an existing IDE would be a perfect fit for what I'm looking for. Commented Dec 8, 2019 at 21:17
  • Ok, the list comprehension shown is a bad example. A better one would be to convert [f('Jane','Bennet'), f('Elizabeth','Bennet'), f('Mary','Bennet')] into [f(s,'Bennet') for s in ['Jane','Elizabeth','Mary']] Commented Dec 8, 2019 at 22:38

1 Answer 1

1

I don't recommend the list comprehension refactor. It would be harder to read as list comprehensions are intended strictly as a concise notation for the iterative generation of a list. If your editor has a rectangular selection feature, you can do this:

# First tab the sirnames out away from the given names. (They don't need to be neatly
# aligned like this, you can just copy paste a bunch of spaces.)
print('Jane',         'Bennet')
print('Elizabeth',    'Bennet')
print('Mary',         'Bennet')

# Use rectangular selection to get rid of the sir names and the print statements,
# leaving the commas. An editor like Geany will also allow you to get rid of the
# trailing whitespace, making your code easier to navigate.
'Jane',
'Elizabeth',
'Mary',
# Add a variable initialization followed by square brackets around the given names.
# You can also pretty it up by indenting or deleting newlines as you see fit.
givenNames = [
  'Jane',
  'Elizabeth',
  'Mary',
]
# Add your for loop.
givenNames = [
  'Jane',
  'Elizabeth',
  'Mary',
]
for name in givenNames:
    print(f"{name} bennet")
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.