kes
kes

Reputation: 6167

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

Upvotes: 20

Views: 57915

Answers (3)

MangMang
MangMang

Reputation: 447

i think this way is better:

my_list = my_list.insert(0,my_string)
my_tuple = tuple(my_list)

Upvotes: -3

dfan
dfan

Reputation: 5814

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.

Upvotes: 1

BoltClock
BoltClock

Reputation: 723668

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

my_tuple = tuple([my_string] + my_list)

Upvotes: 22

Related Questions