1

If the original code is

variable = [line.rstrip().lstrip() for line in fin]

Hypothetically, if I want to break out the list comprehension, would it be the following?

variable = [] # (Do I need to create an empty [] here?)

for line in fin:
    variable = line.rstrip().lstrip()

Thank you for your help!

Mark
  • 90,562
  • 7
  • 108
  • 148
  • 2
    Instead of `variable = ` use `variable.append()` – Mark Oct 03 '20 at 22:11
  • 1
    Another phyrric victory for one-liners. Life is far simpler if we all simply write the for loops: it’s easier to write, it’s easier to understand, it’s easier to debug and it’s easier to modify. – DisappointedByUnaccountableMod Oct 03 '20 at 22:18
  • 2
    Why not using `.strip()` Instead of `.lstrip().rstrip()` – adir abargil Oct 03 '20 at 22:22
  • @barny: You think *this* is a case where the listcomp is harder to read? Really? Sure, the OP should have used `.strip()` instead of `.lstrip().rstrip()`, but aside from that, this is *really* straightforward and easy to read if you have any experience with listcomps. Anyone that writes it as a plain `for` loop with `append`s is someone who is writing some other language in Python (same as the folks who spend a lot of time writing `for i in range(len(someseq))` and doing `someseq[i]` over and over). – ShadowRanger Oct 03 '20 at 22:30
  • 1
    And as opposed to @barny, I frequently find one-lines much clearer and cleaner. `variable` gets a value assigned to it once, and then (I hope) is never modified. WIth a loop, I have to find all occurrences of `variable` to know what's going on. – Frank Yellin Oct 03 '20 at 22:33
  • @ShadowRanger i agree, simplest possible example: and your point is? – DisappointedByUnaccountableMod Oct 04 '20 at 08:32
  • @FrankYellin yes I agree that single reference to `variable` is the the one positive aspect of the one line of code. In the hands of a knowledgeable coder comprehensions are very effective, hence the duplicates and questions about comprehensions. – DisappointedByUnaccountableMod Oct 04 '20 at 08:37

1 Answers1

3

Your code would store the last line in fin with the rstrip() and lstrip() methods applied to it

The comprehension is actually doing the following:

variable = [] #yes because it hasn't been created

for line in fin:
    variable.append(line.rstrip().lstrip())

and as suggested in the comments for this post you can also simplify this by just using: variable.append(line.strip())

Ironkey
  • 2,568
  • 1
  • 8
  • 30
  • @BeginnerCoder no problem! if you liked the answer you can click the green checkmark to accept the answer for other people who might have the same question! Thanks for asking and happy coding! – Ironkey Oct 04 '20 at 17:09