Adele Qian
0
Q:

python get first n elements of list

a=list((1, 2, 3))
n=1
a[:n]

output:
[1]
2
# Python3 code to demonstrate  
# to get first and last element of list 
# using list indexing 
  
# initializing list  
test_list = [1, 5, 6, 7, 4] 
  
# printing original list  
print ("The original list is : " +  str(test_list)) 
  
# using list indexing 
# to get first and last element of list 
res = [ test_list[0], test_list[-1] ]  
  
# printing result 
print ("The first and last element of list are : " +  str(res)) 
4
l = [1, 2, 3, 4, 5]
print(l[:3])
0
an_array = [1,2,3,4,5]
first element = an_array[0]
0

New to Communities?

Join the community