python question | SoloLearn: Learn to code for FREE!

+1

python question

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

3/2/2021 7:19:13 PM

Parham Shafiei Sabet

13 Answers

New Answer

+9

Ярослав Вернигора(Yaroslav Vernigora) Thank you for your kind words, but I just realized that I am not the god of Python out of two reasons: 1) my solution is not universal because it does work only properly for lists of an even number of elements 2) my method is too cumbersome 3) iTech deserves to wear the crown of the god of Python because his method is neat and on the point. Because of this I downvoted my posting. 😳

+7

a = [1,2,3,4] b = [[a[i*2+j] for j in range(2)] for i in range(len(a)//2)] print(b) # 🤪

+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)

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

+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.

+1

b = [[a[0],a[1]],[a[2],a[3]]] or simple write it: b = [[1,2],[3,4]]

+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.

+1

Deepesh Patel This method returns a numpy array, not a list. I don't know whether this can be converted into a list.

+1

a = [1,2,3,4] b=[a[0] , a[1]] c=[a[2] , a[3]] print('[',b,',',c,']')

0

b = [a[i:i+2] for i in range(0, len(a) , 2)]

0

a=[1,2,3,4] b=[a[:2],a[2:]] print(b) This will work ☺️

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)

0

a = [1,2,3,4] print("[%s,%s]" %(a[:2],a[2:4]))