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 Answers3

3

Use slicing:

for data in Mylist[:3]:

or:

for data in Mylist[2:]:

Related: Python's slice notation

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
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
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • 1
    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 Jan 24 '14 at 23:36
  • 1
    @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? – inspectorG4dget Jan 24 '14 at 23:41
  • 1
    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. – abarnert Jan 25 '14 at 00:08
  • 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…) – abarnert Jan 25 '14 at 00:11
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
Nicholas Flees
  • 1,943
  • 3
  • 22
  • 30