Reputation: 5551
I want make an array as follow :
for i in range(0, len(final), 3):
ar.append(
(
final[i] + 100,
final[i+1] + 100,
final[i+2] + 100
)
)
but there is a simple problem. length of final is about 2682715 and i have exception for list index when reach 2682714
with step=3
final[2682714] = OK
final[2682715] = OK
final[2682716] = ERROR
How can i handle that? we can use try/except IndexError
but whole item will be ignored
Upvotes: 0
Views: 745
Reputation: 771
you can use list comprehension:
final = (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15)
ar = []
ar = [final[i:i + 3] for i in range(0, len(final), 3)]
print(ar)
output:
[(1, 2, 3), (4, 5, 7), (8, 9, 10), (11, 12, 13), (14, 15)]
Upvotes: 2
Reputation: 51653
final = range(31)
ar = []
for i in range(0, len(final), 3):
ar.append(tuple(final[i:i+3]))
print(ar)
Output:
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 14), (15, 16, 17), (18,
19, 20), (21, 22, 23), (24, 25, 26), (27, 28, 29),(30,)]
Your list length is divisible by 3 - you last element would be the last triplet , not a tuple with only one element...
Mine is not divisible by 3 without rest, so I have an incomplete tuple
at the end.
Using the list comprehension tuple(final[i:i+3])
will ensure you do not overstep the boundaries of final
and the remaining 1
or 2
numbers are in the last tuple
.
Upvotes: 3
Reputation: 3706
slicing is nice, for one line add a zip
a = [*range(9)]
[*zip(a[::3], a[1::3], a[2::3])]
Out[321]: [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
zip
automatically drops extra elements that don't make up a tripple
Upvotes: 2