How to get the first N elements from a list in Python

3 Answers

0 votes
lst = [34, 78, 90, 'python', 'java', 'c++']

N = 4
new_list = lst[:N]

print(new_list)


     
 
'''
run:
 
[34, 78, 90, 'python']

'''

 



answered Jan 11, 2021 by avibootz
0 votes
lst = [34, 78, 90, 'python', 'java', 'c++']

N = 4
new_list = []
for index in range(0, N):
    new_list.append(lst[index])

print(new_list)


     
 
'''
run:
 
[34, 78, 90, 'python']

'''

 



answered Jan 11, 2021 by avibootz
0 votes
lst = [34, 78, 90, 'python', 'java', 'c++']

N = 4
new_list = [item for index, item in enumerate(lst) if index < N]

print(new_list)


     
 
'''
run:
 
[34, 78, 90, 'python']

'''

 



answered Jan 11, 2021 by avibootz

Related questions

1 answer 125 views
1 answer 139 views
1 answer 181 views
...