How can I create a nested list and put a specific amount of elements in each nest? list and It's nested elements always not the same

Viewed 198

This is what I am doing,

    amount = [2, 2, 3]
my_list = ['name_zero', 'name_one', 'score_three', 'score_nine', 'age_zero', 'age_ten', 'age_six']
output = []

for i in amount:
    output.append(my_list[:i])

print(output)
  • what I am getting:

    [['name_zero', 'name_one'], ['name_zero', 'name_one'], ['name_zero', 'name_one', 'score_three']]

The problem with my code is, It is appending the same elements, what should be the right approach to receive output like this?

# [['name_zero', 'name_one'], ['score_three', 'score_nine'], ['age_zero', 'age_ten', 'age_six']]
4 Answers

Try:

amount = [2, 2, 3]
my_list = [
    "name_zero",
    "name_one",
    "score_three",
    "score_nine",
    "age_zero",
    "age_ten",
    "age_six",
]
output = []

i = iter(my_list)
for v in amount:
    output.append([next(i) for _ in range(v)])

print(output)

Prints:

[
    ["name_zero", "name_one"],
    ["score_three", "score_nine"],
    ["age_zero", "age_ten", "age_six"],
]

One way to do this is to keep track of the start index and then length of each list

amount = [2, 2, 3]
my_list = ['name_zero', 'name_one', 'score_three', 'score_nine', 'age_zero', 'age_ten', 'age_six']
output = []

start_index = 0
for list_len in amount:
    output.append(my_list[start_index:(start_index + list_len)])
    start_index += list_len

print(output)

Actually you have to specify the starting index of your output.append(my_list[:i]) because it is changing for every iteration. This should do.

amount = [2, 2, 3]
my_list = ['name_zero', 'name_one', 'score_three', 'score_nine', 'age_zero', 'age_ten', 'age_six']
output = []
j = 0
for i in amount:
    output.append(my_list[j:j+i])
    j += i

print(output)

Output:

[['name_zero', 'name_one'], ['score_three', 'score_nine'], ['age_zero', 'age_ten', 'age_six']]

Edit: There's a more pythonic way to do the same thing:

output = [my_list[sum(amount[:i]):sum(amount[:i+1])] for i in range(len(amount))]

You may also consider this one:

output = iter(my_list)
output = [[next(output) for i in range(i)] for i in amount]

This should do the trick:

amount = [2,2,3]
my_list = ['name_zero', 'name_one', 'score_three', 'score_nine', 'age_zero', 'age_ten', 'age_six']
output = []

for i in amount:
    count = 0
    current_list = []
    while count < i:
        current_list.append(my_list.pop(0))
        count += 1
    output.append(current_list)

print(output)

['name_zero', 'name_one'], ['score_three', 'score_nine'], ['age_zero', 'age_ten', 'age_six']]
Related