Home > Blockchain >  for loop but start at middle Python
for loop but start at middle Python

Time:09-26

Does anyone know is it possible to start at the element ['d'] instead of ['a'] with this code? I thought may be putting y 3 but that doesn't seem to work.

list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]
for y in list_:
    print(y)

This code prints:

['a']
['b']
['c']
['d']
['e']
['f']
['g']
['h']

But I want it to print:

['d']
['e']
['f']
['g']
['h']

CodePudding user response:

list = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]
for y in range(3,len(list)):
    print(list[y])

this will output what you want

CodePudding user response:

You can "slice" the list within the loop as follows:

list = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]
for y in list[3:]:
    print(y)

or, you can use range where the first parameter is the starting point.

for y in range(3, len(list)):
    print(list[y])

CodePudding user response:

One solution is to slice the list before you iterate over it:

for y in list[3:]:
    print(y)

CodePudding user response:

Using islice :

from itertools import islice

list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]

for y in islice(list_, list_.index(['d']), None):
    print(y)

with a flag:

start = False

list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]

for y in list_:
    if y == ['d']:
        start = True
    if start:
        print(y)

or simply using slicing:

list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]

for y in list_[list_.index(['d']):]:
    print(y)

Also try to rename your variable because list is the Python list class.

CodePudding user response:

I don't know if you are trying to start at the middle, but no matter how many itens there are you can do this:

list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]

for y in list_[int(len(list_)/2):]:
    print(y)

it will check the number of itens and divide it by 2 and cast it as an integer value. The loop will begin from there.

  • Related