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).
In this method, we convert the string to list and then append to target list and then convert this result list to tuple using tuple(). This is another way in which this task can be performed. In this, we convert the string and list both to tuple and add them to result tuple.
Using the tuple() built-in function An iterable can be passed as an input to the tuple () function, which will convert it to a tuple object. If you want to convert a Python list to a tuple, you can use the tuple() function to pass the full list as an argument, and it will return the tuple data type as an output.
Python's built-in function tuple() converts any sequence object to tuple. If it is a string, each character is treated as a string and inserted in tuple separated by commas.
I can't speak for performance, but this is definitely the simplest I can think of:
my_tuple = tuple([my_string] + my_list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With