1

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

3 Answers 3

3

Use slicing:

for data in Mylist[:3]:

or:

for data in Mylist[2:]:

Related: Python's slice notation

Sign up to request clarification or add additional context in comments.

1 Comment

Can't get any simpler.
1

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

4 Comments

This is worth knowing about, but usually not worth doing with a sequence. If the slice is big enough that the copying cost matters, it's likely also big enough that the cost of manually skipping over the first n elements also matters. (For example, if a = list(range(100000)), a[50000:60000] is about 10x faster than list(islice(a, 50000, 60000)). Of course when you have an iterable that may not be a sequence, that's a different story…
@abarnert: that's really cool. Out of sheer morbid curiosity: is there a timing difference in a[50000:60000] between python2.7 and python3.3?
Good question. Python.org 64-bit CPython 3.3.2: 34.2µs slice, 291µs islice. Apple 64-bit CPython 2.7.5: 32.0µs slice, 344µs islice. So it looks like no significant change in slices, but islice got a little faster.
Of course that isn't a totally fair test—putting the islice in a list like that means you don't save any of the list allocation/construction time that looping over an islice can avoid. But if I try with collections.deque(maxlen=0), which is about as close to consuming an iterator with no overhead as you can get, it just drops to 281µs/306µs. (Of course the real win is when you don't have enough memory, at least without swapping…)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.