简体   繁体   中英

Python: Difference in iteration over tuple and list in list-comprehension?

My goal: Understand why the following function "change" behaves differently for the inputs "list of a single tuple" and "tuple of a single tuple".

I use the list comprehension in "change" in a different program and was surprised to find that the two inputs behaved differently.

def change(entries):
    return ['\t'.join(entry) for entry in entries]

entry_tuple_list = [('val1', 'val2')]
print(change(entry_tuple_list)) #Evaluates to ['val1\tval2']

entry_tuple_tuple = (('val1', 'val2')) 
print(change(entry_tuple_tuple)) #Evaluates to ['v\ta\tl\t1', 'v\ta\tl\t2']

expected_result = ['val1\tval2']

I would have expected both entry_tuple_list and entry_tuple_tuple to display the same behaviour in the function and turn into the expected_result of ['val1\tval2'] .

That is not the case as you can see in the code-comments. Why do these two inputs cause different outputs?

Because your entry_tuple_tuple = (('val1', 'val2')) is not a tuple of tuples. To let python know you want a one-element tuple, slip in a comma, ie changing that line to entry_tuple_tuple = (('val1', 'val2'),) produces the expected result.

As it stands, it is just picking up a single tuple with two values. Your comprehension is iterating over the characters in each of those two values.

Having this (()) doesnt mean you have 2 tuples . Let us understand what is happening here:

this entry_tuple_tuple[0] will output val1

while this entry_tuple_list[0] will output ('val1', 'val2')

so what's wrong here? Indeed in python if you want to have a tuple then you should have , .

In here for instance, a = (12) is an integer and not a tuple as you would expect. to make it a tuple you can do this a = 12, . now a is a tuple, and guess what! you don't even need () .

To solve your problem, just add , as here: entry_tuple_tuple = (('val1', 'val2'),) . That should get you nested tuples as you want. I hope you get it by now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM