'how do you convert a list into a int in python in one/two lines?
If you want to convert a list into a int
You could use
x = ""
the_list = [5,7,8,6]
for integer in the_list:
x+=str(integer)
ans = int(x)
#output
5786
is there a shorter way for doing this? Thanks for helping
Solution 1:[1]
str has a join method, where it takes a list as an argument and joins each element by given string.
For example you can create a comma separated line as such:
the_list = ["foo", "bar"]
print(",".join(the_list))
result:
foo,bar
Remember, all elements of the list must be strings. So you should map it first:
the_list = [1, 2, 3, 4]
print(int("".join(map(str, the_list))))
result:
1234
Solution 2:[2]
what you could do for this is use list comprehension to turn your list of values into a list of strings. Then you could use the .join method to join the list of strings together. For example:
string_list = [str(num) for num in list]
integer = "".join(string_list)
An example with a list:
list = [3, 4, 5]
string_list = [str(num) for num in list]
integer = "".join(string_list)
print(integer)
Output:
345
The .join() method allows you do combine string list values together with your desired character being specified in the "" quotation marks. List comprehension is a shortcut to make a for loop inside of a list.
Solution 3:[3]
If your list is in the form: [1,5,3,11]
You can use:
lst = [1, 5, 3, 11]
x = int("".join([str(x) for x in lst]))
>>> x
15311
Solution 4:[4]
The sum() function will sum all elements in the list.
Example:
ints = [1, 3, 5, 7]
print(sum(ints, 0))
Where 0 is the starting index, and ints is your list (not required)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Alan Shiah |
| Solution 3 | |
| Solution 4 | Zack Walton |
