-1
list1=[1,2,3,4,5,6]
for x in range(len(list1)):
 print("{}+{}".format(list1[x],list1[x+1]))
 print(list1[x]+list1[x+1])

this is giving me 1+2=3, 2+3=5, 3+4=7, 4+5=9, 5+6=11. what I want as an out put is : 1+2=3, 3+4=7, 5+6=11

james
  • 23
  • 4
  • Add a step of 2 to your range – DarkKnight Mar 12 '23 at 14:13
  • The third argument to `range` is a step which decides how much `x` gets incremented by each loop. – Carcigenicate Mar 12 '23 at 14:13
  • Exactly the same problem: [how to print values from a python list in pairs without printing already printed index values](https://stackoverflow.com/questions/75673423/how-to-print-values-from-a-python-list-in-pairs-without-printing-already-printed) – Matthias Mar 12 '23 at 15:01

2 Answers2

0

What you want to do is go through the list in pairs, so change the step argument of range() to 2:

list1=[1,2,3,4,5,6]
for x in range(0, len(list1)-1, 2):
  print("{}+{}".format(list1[x],list1[x+1]))
  print(list1[x]+list1[x+1])

See the range() function documentation for more.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 2
    You can also make the print statement more readable by using: print(f"{list[x]}+{list[x+1]} = {list[x] + list[x+1]}") instead of using format – Peter Burkert Mar 12 '23 at 14:16
0
list1=[1,2,3,4,5,6]
for x in range(0,len(list1)-1,2):
    print("{}+{}={}".format(list1[x],list1[x+1],(list1[x]+list1[x+1])))

OUTPUT

1+2=3

3+4=7

5+6=11