AF2k15 AF2k15 - 8 days ago 4x
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] ]

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'
print 'p0 found'
print combo[3:4]

The output:

p0 found

Thanks all.

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