1

I am very confused on why the following two for-loop scenarios generate different outputs, starting from the same list of lines:

 print lines
   ['175.11\n', '176.39\t56.887\n', '178.17\n', '176.1\t51.679\n', '176.1\t51.679\n', '175.15\n', '176.91\t32.149\t30.344\n', '182.33\n', '173.04\n', '174.31\n']

SCENARIO #1: Bracketed for-loop

When I run the following:

lines = ["Total = "+line for line in lines]
print lines

lines becomes:

['Total = 175.11\n', 'Total = 176.39\t56.887\n', 'Total = 178.17\n', 'Total = 176.1\t51.679\n', 'Total = 176.1\t51.679\n', 'Total = 175.15\n', 'Total = 176.91\t32.149\t30.344\n', 'Total = 182.33\n', 'Total = 173.04\n', 'Total = 174.31\n']

SCENARIO #2: Un-bracketed for-loop

But, when I run this:

for line in lines:
    lines = ["Total = "+line]
print lines

lines becomes only:

['Total = 174.31\n']

I would greatly appreciate any help explaining what's going on here! (Also, I should mention that I am more interested in the output from SCENARIO #1, but would like to accomplish it using the format of SCENARIO #2).

Dennis
  • 111
  • 6
  • 2
    Have you read [the Python tutorial](https://docs.python.org/tutorial)? What you are calling a "bracketed for loop" is in fact a list comprehension, which is not a for loop at all (although it has some similarities). – BrenBarn Oct 10 '15 at 21:47
  • 1
    Ahh OK, thank you @BrenBarn! I didn't realize that...I didn't know how else to google "for loop in brackets". That explains a lot now. – Dennis Oct 10 '15 at 21:49

1 Answers1

3

You are overwriting your list of each loop iteration, as opposed to appending to it.

The fix would be:

myList = []
for line in lines:
    myList.append("Total = " + line) # appends the r-value to your list

But I still prefer list comprehension for its conciseness, anyway.

You can also use condition list comprehension:

# excludes empty lines
myList = ["Total = "+line for line in lines if len(line) > 0]

You are modifying a list that you are iterating through

As your for loop progresses through your lines you are appending new items. Any time you modify a container you are iterating through the results can be damaging. Read this question.

Community
  • 1
  • 1
Aidan Gomez
  • 8,167
  • 5
  • 28
  • 51