+ 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! "🎵

3rd Jan 2019, 12:35 PM
Linou Saoudi
Linou Saoudi - avatar
8 ответов
+ 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 : )
3rd Jan 2019, 2:46 PM
Ipang
+ 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)
3rd Jan 2019, 12:52 PM
Hatsy Rei
Hatsy Rei - avatar
+ 5
def convert_list(l): rv = 0 for n in l: rv = rv * 10 + n return rv Hth, cmiiw
3rd Jan 2019, 12:45 PM
Ipang
+ 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]))
3rd Jan 2019, 1:13 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
You're welcome Linou, keep moving on 👍
4th Jan 2019, 3:04 AM
Ipang
+ 1
Thank you very much. Can you just explain the lines you wrote please? Cause I didn't understand everything 😅
3rd Jan 2019, 12:49 PM
Linou Saoudi
Linou Saoudi - avatar
+ 1
Ipang Thank you so much, I got it! :)
3rd Jan 2019, 7:54 PM
Linou Saoudi
Linou Saoudi - avatar
0
Thanks but I want to use a return not print 😅
3rd Jan 2019, 12:57 PM
Linou Saoudi
Linou Saoudi - avatar