Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop syntax in Python without using range() or xrange()

Tags:

python

syntax

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.

like image 422
Rahul Nori Avatar asked Nov 17 '15 14:11

Rahul Nori


People also ask

What can I use instead of range in Python?

The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python 3, there is no xrange, but the range function behaves like xrange in Python 2. If you want to write code that will run on both Python 2 and Python 3, you should use range().

How do you use for loop without in Python?

Looping without a for loopGet an iterator from the given iterable. Repeatedly get the next item from the iterator. Execute the body of the for loop if we successfully got the next item. Stop our loop if we got a StopIteration exception while getting the next item.

What is the use of range () function in for loop?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.


2 Answers

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
like image 74
lejlot Avatar answered Sep 28 '22 01:09

lejlot


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

for index, item in enumerate(lst):
    for j in lst[index+1:]:
        #Do Something
like image 33
turbulencetoo Avatar answered Sep 28 '22 02:09

turbulencetoo