0

I had a problem with a for loop in a python script. The problem is meanwhile solved, but I do not understand the necessity of the comma that solved the issue.

this was the faulty for loop:

variable= (["abc.com", ["", "test"]])
for a,b in variable:
print(a,b)

result:

Traceback (most recent call last):
File "", line 1, in
ValueError: too many values to unpack (expected 2)


this repaired the faulty for-loop:

variable= (["abc.com", ["", "test"]],)
for a,b in variable:
print(a,b)

result:

abc.com ['', 'test']

Why is this comma necessary before the closing bracket? If I extend the content inside the variable, there is no comma necessary at the end.

without comma at the end:

variable= (["abc.com", ["", "test"]], ["xyz.com", ["", "test2"]])
for a,b in variable:
print(a,b)

result:

abc.com ['', 'test']
xyz.com ['', 'test2']


with comma at the end:

variable= (["abc.com", ["", "test"]], ["xyz.com", ["", "test2"]],)
for a,b in variable:
print(a,b)

result:

abc.com ['', 'test']
xyz.com ['', 'test2']

Any idea why there is sometimes the last comma necessary and sometimes not?

Thanks

1 Answer 1

2

The assignment of variable in your first example is equivalent to

variable = ["abc.com", ["", "test"]]

i.e, the value will be a single list; the outer parentheses are redundant. When you loop over that, the first item is the string "abc.com", which won't match a, b — there are too many letters. By adding a comma after the list, you turn the expression into a tuple. If you have more than one element, there is already a comma there (after the first element), so you don't need to add another one.

The takeaway is: Parentheses don't make tuples; commas do! Consider the following assignments

x = 1   # Integer
x = (1) # Also integer
x = 1,  # One-element tuple
x = (1,) # Also one-element tuple
x = 1,2  # Two-element tuple
Sign up to request clarification or add additional context in comments.

Comments

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.