user3224813
user3224813

Reputation: 85

Python list loop from a index

I have a list of dic

MyList=[
    {'Buy': 'Yes', 'date': monday, 'item': '1234'},
    {'Buy': 'Yes', 'date': monday, 'item': '4'},
    {'Buy': 'Yes', 'date': sunday, 'item': '134'},
    {'Buy': 'Yes', 'date': sunday, 'item': '124'},
    {'Buy': 'Yes', 'date': friday, 'item': '14'},
    {'Buy': 'Yes', 'date': friday, 'item': '234'}
]

I use a loop

for data in Mylist:

so it will go through all the items

if I want to do the same but I want to choose the begin and the end of le loop for example a loop start from 0 to 3 or a loop from 2 to end how can I do that?

thanks in advance

Upvotes: 1

Views: 90

Answers (3)

inspectorG4dget
inspectorG4dget

Reputation: 113905

To loop through the first n elements:

for i in itertools.islice(L, 0, n):
    # do stuff

To loop through the last n elements:

for i in itertools.islice(L, len(L)-n, len(L)):
    # do stuff

To loop through the first n and the last m elements:

for i in itertools.chain(itertools.islice(L, len(L)-n, len(L)), itertools.islice(L, len(L)-m, len(L))):
    # do stuff

Upvotes: 1

Nicholas Flees
Nicholas Flees

Reputation: 1953

If you were interested in printing items 0 through 3, for example, you could do something like this:

for item in MyList[:3]:
    print item

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

Use slicing:

for data in Mylist[:3]:

or:

for data in Mylist[2:]:

Related: Python's slice notation

Upvotes: 3

Related Questions