Dennis
Dennis

Reputation: 111

Difference between unbracketed v. bracketed 'for loop' in python?

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).

Upvotes: 1

Views: 135

Answers (1)

Aidan Gomez
Aidan Gomez

Reputation: 8627

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.

Upvotes: 3

Related Questions