Python Coding Day 11 | Python List : index, count, sort

Python List : index, count, sort

Watch the lesson tutorial  ðŸ”»


Python lists are one of the most versatile built-in data structures. They are used to store collections of items and they have many powerful methods for manipulating that data.

1. list.index(): Finding the Position of an Item

The index() method returns the index (position) of the first occurrence of a specified item within the list. You can optionally specify start and end indices to limit the search range. If the item is not found, it raises a ValueError.

💻 Code Examples: index()

Python
# Basic search for the first occurrence
fruits = ['apple', 'banana', 'orange', 'banana']
print(fruits.index('banana'))
# Output: 1

# Search starting from index 2
fruits = ['apple', 'banana', 'orange', 'banana']
print(fruits.index('banana', 2))
# Output: 3

# Search within a specific slice (index 0 inclusive, index 2 exclusive)
fruits = ['apple', 'banana', 'orange', 'banana']
print(fruits.index('banana', 0, 2))
# Output: 1

# Example of a ValueError (if the item is not found)
fruits = ['apple', 'banana', 'orange', 'banana']
# print(fruits.index('cherry')) 
# Output: ValueError: 'cherry' is not in list

2. list.count(): Counting Item Occurrences

The count() method returns the number of times a specified item appears in a list. This is useful for analyzing the frequency of data within a collection.

💻 Code Examples: count()

Python
# Counting a number
data_list = [1, 2, 2, 3, 2]
print(data_list.count(2))
# Output: 3

# Counting a string
a = ["A", "B", "C", "A"]
print(a.count("A"))
# Output: 2

# Counting an element that is not present
print(data_list.count(5))
# Output: 0

3. list.sort(): Modifying a List in Place

The sort() method sorts the list in place, modifying the original list directly. It is highly flexible due to its optional parameters: reverse and key.

💻 Code Examples: sort()

Python
# Default ascending numerical sort
num = [4, 2, 9, 1]
num.sort()
print(num)
# Output: [1, 2, 4, 9]

# Descending sort using the reverse parameter
num = [4, 2, 9, 1]
num.sort(reverse=True)
print(num)
# Output: [9, 4, 2, 1]

# Sorting strings based on their length using the key parameter (shortest first)
words = ['apple', 'banana', 'car', 'kiwi']
words.sort(key=len)
print(words)
# Output: ['car', 'kiwi', 'apple', 'banana']

# Case-insensitive alphabetical sort using the key parameter
names = ['Alice', 'Bob', 'charlie']
names.sort(key=str.lower)
print(names)
# Output: ['Alice', 'Bob', 'charlie']

- by Chirana Nimnaka

Comments

Popular posts from this blog

Python Coding Day 1 | The print() Function and Comments

What is Python?

Set Up an Environment to Code in Python