Table of Contents
ToggleIn Python, a list is an ordered collection of elements. Each element in a list corresponds to an index, starting from 0. This guide explains how to access list items using indexing, negative indexing, slicing, and extracting sublists.
To access an item in a list, use square brackets [] and specify the index of the element. The index starts at 0 for the first element and increments by 1 for each subsequent element.
list1 = ["Rohan", "Physics", 21, 69.75]
list2 = [1, 2, 3, 4, 5]
print("Item at 0th index in list1:", list1[0]) # Output: Rohan
print("Item at index 2 in list2:", list2[2]) # Output: 3Negative indexing allows you to access elements from the end of the list. The index -1 refers to the last element, -2 to the second last, and so on.
list1 = ["a", "b", "c", "d"]
list2 = [25.50, True, -55, 1+2j]
print("Item at -1 index in list1:", list1[-1]) # Output: d
print("Item at -3 index in list2:", list2[-3]) # Output: TrueThe slice operator [start:stop] is used to fetch a range of elements from a list. The start index is inclusive, and the stop index is exclusive. If no indices are provided, it defaults to the entire list.
list1 = ["a", "b", "c", "d"]
list2 = [25.50, True, -55, 1+2j]
list3 = ["Rohan", "Physics", 21, 69.75]
print("Items from index 1 to last in list1:", list1[1:]) # Output: ['b', 'c', 'd']
print("Items from index 0 to 1 in list2:", list2[:2]) # Output: [25.5, True]
print("All items in list3:", list3[:]) # Output: ['Rohan', 'Physics', 21, 69.75]A sublist is a consecutive sequence of elements from the original list. You can extract a sublist using the slice operator with appropriate start and stop indices.
list1 = ["a", "b", "c", "d"]
list2 = [25.50, True, -55, 1+2j]
print("Items from index 1 to 2 in list1:", list1[1:3]) # Output: ['b', 'c']
print("Items from index 0 to 1 in list2:", list2[0:2]) # Output: [25.5, True]Enroll in our Python certification course at Vista Academy and become a certified expert to boost your career.
