Monday, 20 September 2021

Python: get first n items from the list

Approach 1: Using plain iteration.

first_n_elements_1.py

def first_n_elements(my_list, n):
    temp_list = []

    for i in range(n):
        temp_list.append(my_list[i])
    
    return temp_list

list1 = [2, 3, 4, 5, 7, 11, 13, 17]
first_4_elements = first_n_elements(list1, 4)

print("list1 -> ", list1)
print("first_4_elements -> ", first_4_elements)

Output

list1 ->  [2, 3, 4, 5, 7, 11, 13, 17]
first_4_elements ->  [2, 3, 4, 5]


Approach 2: Using ranges

first_n_elements_2.py

def first_n_elements(my_list, n):
    return my_list[:n]

list1 = [2, 3, 4, 5, 7, 11, 13, 17]
first_4_elements = first_n_elements(list1, 4)

print("list1 -> ", list1)
print("first_4_elements -> ", first_4_elements)

 

Output

list1 ->  [2, 3, 4, 5, 7, 11, 13, 17]
first_4_elements ->  [2, 3, 4, 5]

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment