14 AnswersNew Answer
Ярослав Вернигора(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. 😳
a = [1,2,3,4] b = [[a[i*2+j] for j in range(2)] for i in range(len(a)//2)] print(b) # 🤪
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)
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!
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.
b = [[a,a],[a,a]] or simple write it: b = [[1,2],[3,4]]
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.
Deepesh Patel This method returns a numpy array, not a list. I don't know whether this can be converted into a list.
a = [1,2,3,4] b=[a , a] c=[a , a] print('[',b,',',c,']')
b = [a[i:i+2] for i in range(0, len(a) , 2)]
a=[1,2,3,4] b=[a[:2],a[2:]] print(b) This will work ☺️
Bross try to use this method if you're brginner: a = [1,2,3,4] b = [a[0: 2], a[2:4]] print(b)
a = [1,2,3,4] print("[%s,%s]" %(a[:2],a[2:4]))
a=[1,2,3,4] b=[a[:2],a[:2]] print(b) I think this may work check once