Home > other >  how do you convert a list into a int in python in one/two lines?
how do you convert a list into a int in python in one/two lines?

Time:04-04

If you want to convert a list into a int

You could use

x = ""
for integer in the_list:
       x =str(integer)
ans = int(x)

is there a shorter way for doing this? Thanks for helping

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

If you 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

CodePudding user response:

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.

  • Related