Reputation: 435
I wrote a small Python script below that is behaving in a way I did not anticipate, but I cannot pinpoint the error. Specifically, I have a variable xyz_all
that I'd expect to be empty because I'm only ever appending an empty list to it, but in reality it contains the elements of xyz
. How is this possible?
with open(filename,'r') as rf:
xyz = []
xyz_all = []
for line in rf:
if 'A' in line:
line = line.split()
xyz.append([float(j) for j in line[4:7]])
elif 'B' in line:
xyz = []
xyz_all.append(xyz)
print(xyz_all)
Upvotes: 1
Views: 70
Reputation: 140
From your code, xyz will be an empty list of length zero but when you do xyz = [] xyz_all.append(xyz) you are appending an empty list (xyz) to list (xyz_all) which means now xyz_all has one element in it which is an empty list and its length is not zero but 1. xyz_all=[[]] is a list containing an empty list in it.
Upvotes: -1
Reputation: 280564
You only ever append empty lists to xyz_all
, but those lists don't stay empty. When you do
xyz.append([float(j) for j in line[4:7]])
you're appending to a list that may already be an element of xyz_all
.
Upvotes: 3