-1

Bit of a generic noob question. I am heavily dealing with long lists of integer/float values and wasting a lot of time.

my_list = [1,2,3,4,5,6,7,8,9,10.....] etc.

Say I want to pass a portion of that list to a function. It could be the first 3 elements, then the following 3 etc....it could also be in groups of 4,5,6....it might even be required that I take different a different amount of elements each time.

def myfunc(x,y,z):
 do something
 return something

What is the most efficient way to iterate by a specified number of values, as efficiency is always appreciated and these simple iterations are the places where I can gain something.

cc6g11
  • 477
  • 2
  • 10
  • 24

3 Answers3

0
len_ml = len(my_list)
for i in range(0, len_ml, 3):
  chunk = my_list[i:min(len_ml, i+3)]

This is a way. I am not sure that it is the best, though.

bcdan
  • 1,438
  • 1
  • 12
  • 25
0

With a list you can get just the items you want with list[start:end].

So to skip the first list[1:] or last list[:-1] or first 3 and last 3 list[3:-3]

if you don't know how may items are in the list to start you can do a len(list) to get number. So if you had X items and wanted 3 groups :

numberofgroups = len(list) / 3

To do for loop over only certain ones:

start_index=1

end_index=-1

for item in my_list[start_index:end_index]
    print item
Kerry Hatcher
  • 601
  • 6
  • 17
0
>>>my_list = [1,2,3,4,5,6,7,8,9,10]
>>>group_len = 3 #you can change the length as per your requirement i.e 2,3,4,5,6...
>>>for i in range(0,len(my_list)):
       if i*group_len < len(my_list):
           my_list[i*group_len:(i+1)*group_len]
       else:
           break;
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]

Result for group_len = 5

[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
Kousik
  • 21,485
  • 7
  • 36
  • 59