AF2k15 AF2k15 - 1 month ago 6
Python Question

Slicing a range of elements in each sublist?

I suspect there are more than one ways to do this in Python 2.7, but I'd like to be able to print the first three elements of each sublist in combos. Is there a way to do this without a loop?

combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ]


such that the output of a print statement would read:

[ [1,2,3], [5,6,7], [9,10,11], [1,2,3] ]


***AFTER GETTING YOUR SUGGESTIONS:
I was struggling to see how this would work inside of my code structure but list comprehension can be done as part of an if statement like so, which I failed to recognize:

p0combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ]
p0 = [1, 2, 3]

if p0 not in [combo[:3] for combo in p0combos]:
print combo[:3]
print 'p0 not found'
else:
print 'p0 found'
print combo[3:4]


The output:

p0 found
[0.15]


Thanks all.

Answer
print [temp_list[:3] for temp_list in combos]
Comments