Skip to content
Advertisement

Combine list elements to create a nested list

Given a python list with alternating values of two types:

list = ['Q', '0.963', 'R', '0.020', 'K', '0.015', 'E', '0.001']

How can I combine every two values to get something like this:

new_list = [['Q', '0.963'], ['R', '0.020'], ['K', '0.015'], ['E', '0.001']]

Advertisement

Answer

You can simply use range()‘s step parameter and list indexing.

list2 = ['Q', '0.963', 'R', '0.020', 'K', '0.015', 'E', '0.001']
new_list=[list2[i:i+2] for i in range(0,len(list2),2)]
print(new_list)

Output:

[['Q', '0.963'], ['R', '0.020'], ['K', '0.015'], ['E', '0.001']]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement