1

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)

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, that makes a lot of sense. I totally missed that. Thank you.
-1

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.

2 Comments

In the elif loop you reinitialized xyz to an empty list then how can xyz not be empty?
This is not correct. xyz_all contains numerical values at the end of the script.

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.