Home > Enterprise >  Prevent nesting when function used to define tuple
Prevent nesting when function used to define tuple

Time:02-12

I'm trying to define a tuple, but part of what I want to go into the tuple will be the output of a function. This output ends up being nested, which I do not want.

def do_thingy():
    # Example of a fucntion that does things
    return(["c", "d"],["e","f"])

my_tuple = (["a", "b"], do_thingy())
print(my_tuple)

# Returns: (['a', 'b'], (['c', 'd'], ['e', 'f']))
# I want: (['a', 'b'], ['c', 'd'], ['e', 'f'])

I've tried a lot of jiggery-pokery but cannot get the result I desire. As an example:

def do_thingy():
    return[["c", "d"],["e","f"]]
my_tuple = tuple([["a", "b"]   do_thingy()])
print(my_tuple) 

For various reasons I'm trying to keep this to just one line. Not in the least because I'm rewriting this script to make it more readable and easy to modify. If that's not possible I suppose I can put the solution in a function.

CodePudding user response:

I will just type my comment here as an answer for completeness:

def do_thingy():
    return (["c", "d"],["e","f"])
my_tuple = (["a", "b"], *do_thingy())
print(my_tuple) 

The "*" is known as an unpacking operator I believe.

Output:

(['a', 'b'], ['c', 'd'], ['e', 'f'])
  • Related