Indexing and slicing of lists in Python

19-04-23 Ahmed Obaid 2680 0

​Indexing in lists is handled in the same way as it is for strings. There are several ways to print the entire list with all the items, but to print a specific range of list items we use the Slice operation. List slicing is performed using a colon (:). List items can be accessed using square brackets [ ]. The index starts at 0 and ends at -1.

Remember the following figure that we mentioned earlier in the explanation of indexing text strings. It's the same between them.

تذكر الشكل التالي الذي تم ذكره في فهرسة السلاسل النصية الأمر متشابهة بينهم

Explain the concept of indexing and slicing lists:


  • [0] reaches the first element

  • [-4] reaches the fourth element from the end

  • [:2] accesses a list of elements from the third to the last.

  • [:4] accesses a list of elements one through four.

  • [2:4] arrives at a list of elements III through V.

  • [1::2] accesses alternate elements, starting with the second element.



Example:

list = [1,2,3,4,5]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing menu items
print(list[0:6])
print(list[2:4])
# By default, the index value is 0, so it starts at element 0 and goes to index -1.
print(list[:])

The output will be:

 1
 2
 3
 4
 [1, 2, 3, 4, 5]
 [3, 4]
 [1, 2, 3, 4, 5]

 Use negative indexing

 Python enables you to use negative indexing as well. That is, using the index of the list in reverse from the right, where the index of the last element of the right side of the list is -1, followed by the next element on the left at index -2, and so on until the last element on the left is reached.

 Example:

 ​list = [1,2,3,4,5]
 print(list[-1])
 print(list[-2:])
 print(list[:-1])
 print(list[-2:-1])

 The output will be:

 5
 [4, 5]
 [1, 2, 3, 4]
 [4]

 External sources:

 Lists - The official Python documentation

 If you have any questions or concerns, leave them in the comments



Tags


Python python data types python lists Indexing and slicing of lists in Python

Share page