 # Add two consecutive numbers that are user-input as list and store result in list

Hello all, I have no issue on getting user input numbers in the form of list and store it. I would like to know how to add two/user specified consecutive numbers in list and then store the result data as list format.

To be more precise, user enters [1 2 3 4 5 6 7 8 9… (upto n number)]. Now can you write a program to add 1+2; 3+4;5+6;7+8 etc., and store this added data to list like [3 7 11 15…].

Thanks in advance

Separate this into two problems:

• turn the flat list into a list of pairs [[1,2], [3,4], [5,6], …]
• make a new list whose members are the sum of each pair

The former task wants the first element and the one beyond, then the
third element and the one beyond, etc. So if lead element of the pair
has position “i”, the next element has position “i+1”.

So you want to write some kind of loop which starts at i=0 for the first
element, then goes to i=2, then i=4 etc. For each “i”, gather up that
pair and step forward by 2.

There are several ways to do this:

``````L = [1, 2, 3, 4, 5, 6]  # your original list
``````

Step by 2:

``````i = 0
while i < len(L):
... access elements i and i+1 ...
``````

Step by 1, but do it twice inside the loop:

``````i = 0
while i < len(L):
... access element i ...
i += 1
... access element i ...
i += 1
``````

Observe that your step size is a multiplier:

``````i = 0
while i*2 < len(L):
... access element i*2 and element i*2+1 ...
i += 1
``````

Let me introduce you to the range() builtin function. Type “help(range)”
at the Python prompt. It takes arguments start, end, step.

``````for i in range(0, len(L), 2):
... access elements i and i+1 ...
``````

You can also treat the original list as consumable:

``````while len(L) > 0:
... access elements 0 and 1 ...
L.pop(0)
L.pop(0)
``````

Since lists are containers you can simplify the “not empty” test:

``````while L:
... access elements 0 and 1 ...
L.pop(0)
L.pop(0)
``````

because containers are “true” if not empty and 'false" if empty.

Choose wisely,
Cameron Simpson cs@cskk.id.au

1 Like