7

I do not know much about python so i apologize if my question is a very basic one.

Let's say i have a list

lst = [1,2,3,4,5,6,7,8,9,10]

Now what i want to know is that if there is any way to write the following piece of code in python without using range() or xrange():

for i in lst:
    for j in lst after element i: '''This is the line i want the syntax for'''
        #Do Something

The second loop is to access elements after the element i i.e., if i = 3, j would have to loop through from 4 to 10, so the pairs of numbers if i and j are printed would be (1,2)..(1,10), (2,3)...(2,10), (3,4)..(3,10) etc.

I have no idea what to search for or what query to type on any search engine.
Any help would be much appreciated.

Rahul Nori
  • 698
  • 6
  • 17
  • 1
    Possible duplicate of [Iterate over pairs in a list (circular fashion) in Python](http://stackoverflow.com/questions/1257413/iterate-over-pairs-in-a-list-circular-fashion-in-python). Do you want to iterate with the indices `(0, 1), (1, 2), (2, 3)` or `(0, 1), (2, 3), (4, 5)`? – SuperBiasedMan Nov 17 '15 at 14:36
  • Also is there a particular reason you don't want to use `range`? Is it for the sake of challenge/curiosity or something else? – SuperBiasedMan Nov 17 '15 at 14:38
  • @SuperBiasedMan It was just out of curiosity nothing more. – Rahul Nori Nov 17 '15 at 14:44
  • 1
    @SuperBiasedMan No i want to iterate with (0,1)...(0,10), then (1,2)...(1,10), then (2,3)..(2,10), this sort of looping. – Rahul Nori Nov 17 '15 at 14:49
  • Ah, apologies. The link may be helpful but it's not a duplicate then. – SuperBiasedMan Nov 17 '15 at 14:56
  • @SuperBiasedMan Not a problem. It's always better to have more knowledge :) Thank you for the link! – Rahul Nori Nov 17 '15 at 14:59

2 Answers2

8

This is what list slicing is about, you can take part of your list from i'th element through

lst[i:]

furthermore, in order to have both index and value you need enumerate operation, which changes the list into list of pairs (index, value)

thus

for ind, i in enumerate(lst):
    for j in lst[ind+1: ]: 
        #Do Something
lejlot
  • 64,777
  • 8
  • 131
  • 164
7

It looks like you might want to use enumerate():

for index, item in enumerate(lst):
    for j in lst[index+1:]:
        #Do Something
turbulencetoo
  • 3,447
  • 1
  • 27
  • 50
  • lst[index+1] is not a list, it is an element, furthermore, enumerate does not work this way around – lejlot Nov 17 '15 at 14:38
  • Also, I get the order of index and item in `enumerate` wrong every time I try to use it. It's like trying to get a USB in on the first try... – turbulencetoo Nov 17 '15 at 14:45
  • 1
    @turbulencetoo does that also mean that sometimes you get the order right but it still doesn't work so you reflexively try the other way? – Foon Nov 17 '15 at 14:46
  • 1
    I learned something new from your answer. I really appreciate it! – Rahul Nori Nov 17 '15 at 14:51