how do I iteratively add a different number of elements to each item in a list?

57 Views Asked by At

I have a list of elements that occur in order and I'd like to add one at a time to a list.

Desired output:

'first_page'
'first_page + second_page'
'first_page + second_page + third_page'
'first_page + second_page + third_page + fourth_page'

...

Data structure: page_list = ['first_page', 'second_page', 'third_page', 'fourth_page']

How can I get desired output? Thanks!

So far, I'm able to add the next page to the previous page using this function:

new_list = []
for index, elem in enumerate(page_list):
    if(index<(len(page_list)-1)):
        new_list.append(elem + ' + ' + page_list[index+1])
    else:
        new_list.append(elem)

which returns:

['first_page + second_page',
 'second_page + third_page',
 'third_page + fourth_page',
 'fourth_page']
6

There are 6 best solutions below

0
Barmar On

Use join() to create a delimited string.

You can use incrementing slices of the original list as the list to slice.

page_list = ['first_page', 'second_page', 'third_page', 'fourth_page']
new_list = [' + '.join(page_list[:i]) for i in range(1, len(page_list)+1)]

print(new_list)

Or you can keep appending to another list before joining.

new_list = []
pages = []
for page in page_list:
    pages.append(page)
    new_list.append(' + '.join(pages)
0
Ukulele On

One way to do this is to start with new_list containing the first element of page_list and iteratively add the last element of new_list to successive elements of page_list, essentially having a 'running total' stored as the last element of new_list.

This is slightly faster than the other solution as it only does each join once, rather than joining every element of page_list for each element of new_list.

new_list = [page_list[0]] # Initialise new_list with first element of page_list
for elem in page_list[1:]: # For the other elements of page_list
    new_list.append(new_list[-1] + ' + ' + elem) # Add another element of page_list each iteration

print(new_list)
6
rajaa lebchiri On

try this:

pages = []
for index, elem in enumerate(page_list):
    pages.append(page_list[:index + 1])
print(pages)
0
toyota Supra On

How about to do in one line.

pages = [page_list[:index + 1]for index, elem in enumerate(page_list)]
print(pages)
0
somoso On

So lets break down the problem:

  1. We need to iterate over every element in page_list
  2. For every element we iterate over, we need to iterate over all previous elements before it, and add it to a string in the format [a] + [b] + [c] + ... [n]

Because we plan to iterate over each element in the list, but also the ones before it, it is probably wise to use the index of the elements, rather than the elements. This means we should probably make use of the range(start, end) feature.

To start, we can do

page_list = ['first_page', 'second_page', 'third_page', 'fourth_page']

new_list = []

for i in range(0, len(page_list)):
    pass

And now we are iterating over the list. However, inside the for loop, we will probably need to iterate over previous entries too:

page_list = ['first_page', 'second_page', 'third_page', 'fourth_page']

new_list = []

for i in range(0, len(page_list)):
    for j in range(0, i):
        pass

And then we will need a way to build the string - we need to be able to add to the string and handle the case where the string has one and more than one entry:

page_list = [...]

# ...

str = ""

if len(str) > 0:
    str += " + "
str += page_list[index]

And then we put it all together (I changed something, but I'll leave that as an exercise for you to figure out what was the change from above, and why):

page_list = ['first_page', 'second_page', 'third_page', 'fourth_page']

new_list = []

for i in range(1, len(page_list) + 1):
    str = ""
    for j in range(0, i):
        if len(str) > 0:
            str += " + "
        str += page_list[j]
    new_list.append(str)

print(new_list)

It should give:

['first_page', 'first_page + second_page', 'first_page + second_page + third_page', 'first_page + second_page + third_page + fourth_page']
0
Suramuthu R On
page_list = ['first_page', 'second_page', 'third_page', 'fourth_page']
for i in range(len(page_list)):
    sub = page_list[:i+1]
    sub = ' + '.join(sub)
    print(sub)
    
'''Output:
first_page
first_page + second_page
first_page + second_page + third_page
first_page + second_page + third_page + fourth_page
'''