Python List Operations

a) Negative Indexing

Negative indexing is used to access elements from the end of the list.

  • -1 refers to the last element, -2 to the second last, and so on.
fruits = ['apple', 'banana', 'cherry', 'date']
print(fruits[-1]) # Output: 'date'
print(fruits[-3]) # Output: 'banana'

b) Slicing

Slicing allows you to access a portion (sub-list) of the list.

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # Output: [20, 30, 40]
print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[2:]) # Output: [30, 40, 50]

c) index()

The index() method returns the first occurrence index of the specified element.

colors = ['red', 'blue', 'green', 'blue']
print(colors.index('blue')) # Output: 1

d) append()

Adds an element to the end of the list.

Editnumbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]

e) remove()

Removes the first occurrence of the specified value from the list.

fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana')
print(fruits) # Output: ['apple', 'cherry', 'banana']

f) pop()

Removes and returns the element at the given index.
If no index is specified, it removes the last element.

items = ['pen', 'pencil', 'eraser']
items.pop() # Removes 'eraser'
items.pop(0) # Removes 'pen'
print(items) # Output: ['pencil']

g) insert()

Inserts an element at the specified index.

numbers = [1, 2, 4]
numbers.insert(2, 3) # Insert 3 at index 2
print(numbers) # Output: [1, 2, 3, 4]

h) sort()

Sorts the list in ascending order (by default).

nums = [5, 2, 9, 1]
nums.sort()
print(nums) # Output: [1, 2, 5, 9]

You can also sort in descending order:

nums.sort(reverse=True)
print(nums) # Output: [9, 5, 2, 1]

Leave a Reply

Your email address will not be published. Required fields are marked *