+ 1

python question

my code is: a = [1,2,3,4] b = [ ] i want my output to be: b = [[1,2],[3,4]]

2nd Mar 2021, 7:19 PM
Parham Shafiei Sabet
Parham Shafiei Sabet - avatar
12 Answers
+ 4
l = [1, 2, 3, 4, 5, 6, 7, 8, 9] n = 2 x = [l[i:i + n] for i in range(0, len(l), n)] print(x)
2nd Mar 2021, 8:59 PM
iTech
iTech - avatar
+ 3
I'm shocked at how you can use a loop statement without a colon, without a new line without indentation... and it all works! Fantastic! and Markus generally uses two loop statements at once, one after the other... Well, just the God of Python!
2nd Mar 2021, 9:04 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 3
no I am not and I will never pretend it to be. If Guido Von Russom, Nicolas Tesla, Einstein and many Genius Brains speaks in full humble way, why a very normal guy like me should wear a crown? I even hate those qualificative titles. Elon Musk said: A degree was never an intelligence sign! Linus Torvalds said: Show me your code! Who ever like science and appreciate helping others will never react with arrogance and bad behavior, I am one of those. Respect @ Peace.
3rd Mar 2021, 7:39 PM
iTech
iTech - avatar
+ 1
b = [[a[0],a[1]],[a[2],a[3]]] or simple write it: b = [[1,2],[3,4]]
2nd Mar 2021, 8:27 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
Thanks for the compliment â˜ș but I did not reach Python god level yet. Still to study well Django which I already started, AI and ML until I will be Python engineer. The technique called List Comprehension and it is part of python coding terminology. Keep practicing and you will reach master level. Persistence, Perseverance and Practicing. Good Luck.
3rd Mar 2021, 12:57 AM
iTech
iTech - avatar
+ 1
Deepesh Patel This method returns a numpy array, not a list. I don't know whether this can be converted into a list.
4th Mar 2021, 5:15 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
a = [1,2,3,4] b=[a[0] , a[1]] c=[a[2] , a[3]] print('[',b,',',c,']')
17th Apr 2021, 2:47 PM
CAPSPY
CAPSPY - avatar
0
b = [a[i:i+2] for i in range(0, len(a) , 2)]
3rd Mar 2021, 5:27 AM
Calvin Thomas
Calvin Thomas - avatar
0
a=[1,2,3,4] b=[a[:2],a[2:]] print(b) This will work â˜ș
4th Mar 2021, 5:44 AM
Deepesh Patel
Deepesh Patel - avatar
0
Bross try to use this method if you're brginner: a = [1,2,3,4] b = [a[0: 2], a[2:4]] print(b)
4th Mar 2021, 8:29 AM
Muhammad Abdulmalik
Muhammad Abdulmalik - avatar
0
a = [1,2,3,4] print("[%s,%s]" %(a[:2],a[2:4]))
17th Apr 2021, 8:31 PM
CAPSPY
CAPSPY - avatar
0
a=[1,2,3,4] b=[a[:2],a[:2]] print(b) I think this may work check once
3rd Jul 2021, 3:04 AM
K.Lohitha Siri
K.Lohitha Siri - avatar