Naren Murali Naren Murali - 3 months ago 7
Python Question

How to print upto n elements in a list

I want to print upto 50 elements in a list

i.e
If there are 100 elements in the list I need first 50 alone.
My current code for the above is
'Filter':switcheroo.get(zaxis,["None Selected"])[zaxis].unique().tolist()[:50]

If there are 25 elements in the list I need 25 alone.
I get an error when the above code is used.
from other posts I understand that the below code is the solution, but I cant understand how to implement it with my current code.'

[x for _, x in zip(range(n), records)]


How to take the first N items from a generator or list in Python?

Answer

first 50 elements of a list:

    print mylist[:50]

as an iterable:

   print [x for x in mylist[:50]]

Test:

newlist = [x for x in xrange(10)]
newlist2 = [x for x in xrange(100)]

print [x for x in newlist[:50]]
>[1,2,3,4,5,6,7,8,9]
print [x for x in newlist2[:50]]
>[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, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
Comments