Can we convert a list type into any other type like int, string etc.? If yes then please tell how? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can we convert a list type into any other type like int, string etc.? If yes then please tell how?

21st Jul 2019, 7:11 AM
Achal Saxena
Achal Saxena - avatar
6 Answers
+ 4
There is one way to do it as you like. a=5 b ='4' c = [1] print(a + int(b) + int(*c)) # output is 10 print(a + int(b) + int(c[0])) # output is 10 Here the unpac operator '*' is used. But this does only work for one element in the list. int(c[0]) is also possible to use. with the index value you can pick values from a list which holds more than one element.
21st Jul 2019, 8:05 AM
Lothar
Lothar - avatar
+ 4
Here some samples with the * operator: You can use * on iterable objects, by placing it on the left side of the object. lst = [1,2,3] # Unpack to 3 variables: a, b, c = [*lst] #output: a holds 1, b holds 2, ... # Or if you use Tuples to hold data for a volume calculation: vol_tpl = (2, 3, 5) def calc_vol(x, y, z): return x * y * z print(calc_vol(*vol_tpl)) # the * operator splits up the tulpe to the 3 vars: x,y,z #output: 30 The * operator is also very helpful when functions are called with a varying number of arguments def sum_lst(a, *values): sum_ = 0 for i in values: sum_ += i print(sum_) # Now call function with lst:(3 arguments) sum_lst('abc', *lst) #output: 6 # Now call function with lst2:(4 arguments) lst2 = [3,4,5,6] sum_lst('abc', *lst2) #output: 18
21st Jul 2019, 3:38 PM
Lothar
Lothar - avatar
+ 2
As far as I know, python lists aren't typed. You can freely change its type whenever you want
21st Jul 2019, 7:19 AM
Airree
Airree - avatar
+ 2
Uh-oh. You can't do that. Lists cannot be made another datatype. If you can imagine an output that actually makes sense, then it might work, but otherwise it probably doesn't :/
21st Jul 2019, 7:31 AM
Airree
Airree - avatar
+ 1
Means can we do this; a=5, b ='4', c = [1] print(a + int(b) + int(c)) If the code is wrong the how can we print them together?Airree. (edited)---- So I understood that we can use print(a + int(b) +int(*c)) or print( a +int(b) + int(c[0])) Thanks everyone for answering.
21st Jul 2019, 7:28 AM
Achal Saxena
Achal Saxena - avatar
+ 1
Thank you for answering. Please tell a little bit more about unpac operator '*' ---Lothar
21st Jul 2019, 8:09 AM
Achal Saxena
Achal Saxena - avatar