Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a tuple from a string and a list of strings

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).

like image 687
kes Avatar asked Mar 28 '11 02:03

kes


People also ask

How do you create a tuple using a string and using a list?

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.

How do you create a tuple from list?

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.

How do you make a string into a tuple?

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.


1 Answers

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

my_tuple = tuple([my_string] + my_list)
like image 109
BoltClock Avatar answered Sep 25 '22 01:09

BoltClock