0

I've been looking for the answer to this question for a long time, but I couldn't find a solution. I am waiting for your help, thank you in advance. With python

list1 = ["data1","data2","data3","data4","data5"]

output = [    
[list1[0],list1[1]],
[list1[2],list1[3]],
[list1[4]]
        ]
output=[["data1","data2"],["data3","data4"],["data5"]]

How can it provide this output? Can I create a temporary variable in a list and do that.

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
heybelix
  • 35
  • 1
  • 4

2 Answers2

1
list1 = ["data1","data2","data3","data4","data5"]
out = []
i = 0

while True:

    #print("i", i)

    if i == len(list1)-1:
        out.append([list1[-1]])
        break
    elif i > len(list1)-1:
        break
    else:
        out.append([list1[i], list1[i+1]])
    i += 2
print(out)
Shan Ali
  • 564
  • 4
  • 12
0

You are correct. If you print output (e.g. print(output) ) you get

[['data1', 'data2'], ['data3', 'data4'], ['data5']]

which is what your are looking for.

'Output' will be a list of lists which is allowed in python.

Franco
  • 441
  • 3
  • 18