Adrian
Adrian

Reputation: 31

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

Upvotes: 0

Views: 92

Answers (4)

Freddy Mcloughlan
Freddy Mcloughlan

Reputation: 4496

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

Upvotes: 1

niaei
niaei

Reputation: 2399

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

Upvotes: 3

Alan Shiah
Alan Shiah

Reputation: 1086

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.

Upvotes: 1

Zack Walton
Zack Walton

Reputation: 196

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)

Upvotes: 0

Related Questions