Create a tuple from a string and a list of strings

53,383

Solution 1

I can't speak for performance, but this is definitely the simplest I can think of:

my_tuple = tuple([my_string] + my_list)

Solution 2

The straightforward way is simply my_tuple = tuple( my_list + [my_string] ). I would certainly start with that and see if the performance is acceptable before trying to figure out any crazy ways of subverting the normal system for speed.

Share:
53,383
kes
Author by

kes

Updated on July 16, 2022

Comments

  • kes
    kes almost 2 years

    I need to combine a string along with a list of strings into a tuple so I can use it as a dictionary key. This is going to be in an inner loop so speed is important.

    The list will be small (usually 1, but occasionally 2 or 3 items).

    What is the fastest way to do this?

    Before:

    my_string == "foo"
    my_list == ["bar", "baz", "qux", "etc"]
    

    After:

    my_tuple == ("foo", "bar", "baz", "qux", "etc")
    

    (Note: my_list must not be altered itself).