-2

I have ordered list of string elements which I need to iterate.. starting from specific element/item from the list until the end.

The list that I have:

ip_list = ['input1','input2','input3',....,'input10']

I wanted to iterate from any given element (which would be dynamic on each run) for example consider input3 currently till the end of List.

So I wanted to achieve something like this:

for item in ip_list[input3:]:
    # my logic base

I have searched out that, in Python, we can slice the list with positional base but not on value base.

Xantium
  • 11,201
  • 10
  • 62
  • 89
Indrajeet Gour
  • 4,020
  • 5
  • 43
  • 70

4 Answers4

2

Yes using index() finds the position of an element in a list.

So if your list looks like this:

ip_list = ['input1','input2','input3']

And you want to initerate from input3 onward then using ip_list.index('input3') returns the position of input3 (so 2).

You then just have to slice the list in the normal way (as if you were doing ip_list[2:]) but using index():

for item in ip_list[ip_list.index('input3'):]:
    # my logic base

See Finding the index of an item given a list containing it in Python

Xantium
  • 11,201
  • 10
  • 62
  • 89
1

list[list.index(value):]

see https://docs.python.org/3/tutorial/datastructures.html

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Sebastian Loehner
  • 1,302
  • 7
  • 5
0

Here's a solution based on iterators that works with any iterable, not just lists:

def iterate_from(iterable, start_value):
    # step 1: get an iterator
    itr = iter(iterable)

    # step 2: advance the iterator to the first matching value
    first_value = next(value for value in itr if value == start_value)

    # step 3: yield the remaining values
    yield first_value
    yield from itr

Here I used the iter function to get an iterator from the iterable, and the next function to move that iterator forward. You may also be interested in What does the "yield" keyword do?.

You would use it like this:

ip_list = ['input{}'.format(i) for i in range(1, 11)]

for ip in iterate_from(ip_list, 'input7'):
    print(ip)

# output:
# input7
# input8
# input9
# input10
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
-1
ip_list = ['input{}'.format(i) for i in range(1,10)]
for item in ip_list[3:]:
    print(item)
peterevans
  • 34,297
  • 7
  • 84
  • 83