0

I have an array like ['a','b','c','d','e','f']. How can i convert it to an array of arrays such that [['a','b'],['c','d'],['e','f']]

I have tried appending it normally but it give some random result

inputArr = input.split(',')
i=0
Yy = []
while i < len(inputArr):
    temp = [inputArr[i], inputArr[i+1]]
    Yy.append(temp)
    i += 2

Output : [ 'a', 'b,c', 'd,e', 'f' ]

3
  • 3
    it works as expected, print(Yy) gives [['a', 'b'], ['c', 'd'], ['e', 'f']] Commented Apr 7, 2021 at 12:50
  • you code works fine, are u printing inputArr and not Yy? Commented Apr 7, 2021 at 12:58
  • I am taking the input array from sys.argv[1]. I am figuring out if there is an issue with that. I logged the input array from sys.argv[1], It was fine Commented Apr 7, 2021 at 13:03

3 Answers 3

2

I tried your code and got no error. However, if you did, you can try this way:

new_list = [lst[i:i+2] for i in range(0, len(lst), 2)]

This outputs: [['a', 'b'], ['c', 'd'], ['e', 'f']], using list comprehension, which I suppose is what you want.

If you wanted an output of [['a', 'b', 'c'], ['d', 'e', 'f']], then change the i:i+2 to i:i+3 and change (0, len(lst), 2) at the end to (0, len(lst), 3).

Sign up to request clarification or add additional context in comments.

Comments

1

You can use range wich takes (start, stop, step)

lst = ['a','b','c','d','e','f']
new_lst = []
for i in range(0,len(lst), 2):
    new_lst.append(lst[i:i+2])
print(new_lst)

notice that we step twice and slice the list with 2 futher index positions. output: [['a', 'b'], ['c', 'd'], ['e', 'f']]

Comments

1

use can use numpy:

import numpy as np

a = ['a','b','c','d','e','f']
n = np.array(a)
print(n.reshape(3,2))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.