0

I have a for loop that takes an input variable (+1) as the end of its range, and inside it, an if statement that returns factors of said variable:

for i in range(1, int(f)+1):
    if f % i == 0:
        print(i) #temporary

How would I go about adding together the first/last items on the list, then the 2nd/2nd to last items, and so on? I can’t do this manually because the input variable isn’t the same every time.

Raptor_Guy
  • 9
  • 1
  • 4
  • Using a positive index for the first elements and [negative index](https://stackoverflow.com/questions/930397/getting-the-last-element-of-a-list-in-python) for the last values - is a good place to start. – LinkBerest Aug 01 '18 at 15:06

1 Answers1

0

This can be a good start. It likely can be done in less lines but felt this will help you see how negative indexes work.

The list we are looking at is lst = [1, 2, 3, 3, 2, 1]

So the goal would be [2, 4, 6].

Python 2.7

output=[]
lst = [1, 2, 3, 3, 2, 1]
for i in range(int(len(l)/2)):
    print "First: l["+str(i)+"]"str(l[i])
    print "Last: l["+str(-i)+"]"str(l[-i-1])
    output.append(l[i]+l[-i-1])
print output

Python 3.*

output=[]
lst = [1, 2, 3, 3, 2, 1]
for i in range(int(len(l)/2)):
    print("First: l[",i,"]",l[i])
    print("Last: l[",-i,"]",l[-i-1])
    output.append(l[i]+l[-i-1])
print(output)
Zack Tarr
  • 851
  • 1
  • 8
  • 28