+ 1
Can we convert a list type into any other type like int, string etc.? If yes then please tell how?
7 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.
+ 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
+ 2
As far as I know, python lists aren't typed. You can freely change its type whenever you want
+ 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 :/
+ 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.
+ 1
Thank you for answering.
Please tell a little bit more about unpac operator '*' ---Lothar