Printing the First 5 Elements in Python Lists
Python lists are a valuable data structure because they can hold an arbitrary number of values. However, when we want to retrieve the first few elements from a list, it’s important to know how to do t …
Python lists are a valuable data structure because they can hold an arbitrary number of values. However, when we want to retrieve the first few elements from a list, it’s important to know how to do this. Here is one way to do it.
my_list = [10, 20, 30, 40, 50, 60, 70, 80]
print(my_list[:5]) # This will print first 5 elements of list
In the above example [:5]
is called slicing. It means from the start to index 5 (not including index 5). Python returns a new list with elements from the start up to but not including index 5 in this case.
You can also use negative indexing for getting elements from end of the list like, my_list[-5:]
will print last five elements of list.
Remember, slicing is very useful when you want to get a subsection of a list. It can be used with other sequence types (tuples, strings, byte arrays, etc.), not just lists.