Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list of strings to a tuple of ints

I'm new to python and am having trouble doing this conversion. How exactly do you convert a list of individual strings such as ['1','2'] and convert it to a tuple (1,2). If it was simply a list it would be simple to just use tuple(list_x) but this seems more complicated.

like image 561
Alex Avatar asked Nov 30 '25 23:11

Alex


1 Answers

You can use the tuple constructor to make a tuple from a list:

X = ['1', '2']
myTuple = tuple(X)

myTuple is now a tuple of strings: ('1', '2').

If you want to get a tuple of integers, you must first convert your list to a list of integers, and then use the tuple constructor.

The int() function will convert a string to an int. We can use that plus a list comprehension to get what you want:

tuple([int(s) for s in X])
like image 57
Chris Kitching Avatar answered Dec 03 '25 14:12

Chris Kitching



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!