+ 1
How can we convert lists to integers?
Hi, I'm in trouble.đđ I'd like to create a function ( having a list as argument) that converts a list (that contains only numbers) in integers for example [1,2,1,1] will become 1211. I created a for-loop that stops when the length of the list is reached. Then I put a variable that takes all the values of the list elements. The problem is that I want all the elements and when I return the variable, it only returns the last element. Quick overview of my code : def convert_list(list) : for i in range (len(list)) : e = list[i] return e "Please I need somebody help! "đ”
8 Answers
+ 7
Linou Saoudi let's review the code, assume we have a list like this:
[1,2,3,4]
First, prepare a value to return <rv>, and set its value to zero. Next we will iterate the list, and use each list elements' value (that is stored in variable <n>), on each iteration, the <n> value changes into:
1, 2, 3, 4
(1) rv = 0 * 10 + 1 => 1
(2) rv = 1 * 10 + 2 => 12
(3) rv = 12 * 10 + 3 => 123
(4) rv = 123 * 10 + 4 => 1234
There, now we have converted the list into a number, integer to be precise.
Hope it helps clear the doubt : )
+ 7
A method with list operations, in case you need it.
lst = [1,2,1,1]
lstnum = int(''.join([str(x) for x in lst]))
print(lstnum)
+ 5
def convert_list(l):
rv = 0
for n in l:
rv = rv * 10 + n
return rv
Hth, cmiiw
+ 4
Linou Saoudi It's very easy to convert what I gave you to a function which returns an int. It would have been great if you could work on that yourself.
def convert_list(lst):
return int(''.join([str(x) for x in lst]))
+ 2
You're welcome Linou, keep moving on đ
+ 1
Thank you very much. Can you just explain the lines you wrote please? Cause I didn't understand everything đ
+ 1
Ipang Thank you so much, I got it! :)
0
Thanks but I want to use a return not print đ