Search code examples
pythonloops

How to iterate through a python list to get each additional list element?


I have a python list that I need to iterate through to get the additional consecutive element.

I'm trying to make a string from every other consecutive element in my list named data

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ...]

I need to turn this into a string that reads like...

data_string = "1, 3, 6, 10"

The list data can have any number of elements and may change, but the string should always to consist of elements 1,3, 6, 10, 15, 21, and so on.

I've tried running the following function...

def create_lists(values_list):
    result = [[]]
    for value in values_list[1:]:
        new_lists = [curr_list + [value] for curr_list in result]
        result.extend(new_lists)
    return result

result = create_lists(values_list)
print(result)

This only prints out separate lists with individual elements.

I'm new to python and having trouble. Any ideas?


Solution

  • Based on the latest comment:

    data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
    
    i, c, out = 0, 2, []
    while i < len(data):
        out.append(str(data[i]))
        i += c
        c += 1
    
    print(", ".join(out))
    

    Prints:

    1, 3, 6, 10