Skip to content
Advertisement

How to create new list of lists using for loop

I have two lists like

values = [['bert', '1234', 'xxx', 50], ['ernie', '5678', 'fff', 100]]
required = [1, 3]

I want to extract the required elements 1 and 3 from each list contained in values, to create a new list of lists like [['1234', 50], ['5678', 100]].

I was able to solve the problem with a list comprehension:

[[x[y] for y in required] for x in values]

But how can I write the equivalent with explicit for loops?

I tried:

new_list = []
for x in values:
    for y in required:
        new_list.append(x[y])

but the resulting new_list is a single flat list ['1234', 50, '5678', 100].

Advertisement

Answer

You can make a new array before second looping, and then add x[y] in that array. Add the new array to the new_list after the second looping.

new_list = [] 
for x in values:
    temp_list = []
    for y in required:
       temp_list.append(x[y])
    new_list.append(temp_list)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement