In Python, a list is a built-in data structure used to store a collection of similar or dissimilar elements.
Elements in the list can be integers, strings, objects, other lists, and more.
Lists are mutable, meaning elements inside them we can modify by adding, deleting, or changing without disturbing the sequence of elements. Elements are indexed, starting from 0 (first) to n-1 (last). Moreover, data items in the list are arranged in a specific sequence.
Key Characteristics of the list:
1. Dynamic: Memory is dynamically allotted in the list, meaning it can grow or shrink in size as you add or remove elements.
2. Similar/Dissimilar: A list can hold both similar and dissimilar kinds of data. For example, you can store integer and string elements in the same list.
3. Indexing: The list is indexed, starting from 0 (first) to n-1 (last).
Let’s now understand basic list operations and techniques to find an index of items.
What is the basic list of operations and techniques to find an index of items?
1. Creating List –
Candidate = ["John", 12, "Smith", ["Data science" , "98" ] ]
2. Adding items to list –
Using append():
# List of recorded daily temperatures
temperature_data = [10, 15, 18, 22, 20]
# Adding new temperature data
temperature_data.append(24)
# Displaying the updated temperature data
print("Updated temperature data:" , temperature_dataOutput:
Updated temperature data: [ 10,15,18,22,20,24]
add at specific index using insert():
# List of recorded daily temperatures
temperature_data = [10, 15, 18, 22, 20]
# Adding new temperature data at index 2
temperature_data.insert(2, 13)
# Displaying the updated temperature data
print("Updated temperature data:" , temperature_data )Output:
Updated temperature data: [ 10,15,13,18,22,20]
Two or more lists can be concatenated using the + operator.
concatenated_temp = temp_data_1 + temp_data_2
# List of recorded daily temperatures
temp_data_1 = [10, 15, 18]
temp_data_2 = [22, 20]
# Concatenating two lists
concatenated_temp = temp_data_1 + temp_data_2
# Displaying the combined temperature data
print("Combined temperature data:" , concatenated_temp)Output:
Combined temperature data: [10, 15, 18, 22, 20]
How to find the index of an item in a List?
1. `index()` Method:
The foremost method to find an index of a particular element is by making use of Python’s in-built `index` method. `index()` function is used to find an index of the first occurrence of the specified item.
Syntax –
list.index(item[, start[, end]])
list: The list in which you want to search for the item.
item: The value you want to find the index of.
start (optional): The index at which the search starts. Default is 0.
end (optional): The index at which the search ends. Default is the end of the list.
If the specified item is present in the list, it returns the index value of that item. If the item is not present. it will raise `ValueError`.
Optional start and end parameters
We can pass start and end parameters to restrict the search operation to a specific range inside the list.
cricket_scores = [10, 23, 122, 55, 88, 3, 23, 6,11, 37, 12] index = cricket_scores.index(23, 2) # Returns 6 (the second occurrence of 23, starting from index 2)
2. Using Loop for index:
We can iterate through a list by comparing each data item with the target item to find its index. This
approach becomes handy when finding multiple occurrences of target items.
def find_indices(lst, target): indices = [] for index, item in enumerate(lst): if item == target: indices.append(index) return indices cricket_scores = [10, 23, 122, 55, 88, 3, 23, 100, 11, 37, 12, 23, 100, 0, 93, 97] indices = find_indices(cricket_scores, 100) # Returns [7, 12, 13] print(indices)
Output:
[7, 12, 13]
3.using `enumerate()` within a loop:
The enumerate() function can be used in combination with a loop in Python to iterate over both indices and items simultaneously. If you want to explore different types of loops in Python, our article on What is Loop in Python? explains for-loops, while-loops, and for-each loops with examples.
def find_indices(lst, target):
indices = []
for index, value in enumerate(lst):
if value == target:
indices.append(index)
return indices
cricket_scores = [10, 23, 122, 55, 88, 3, 23, 100, 11, 37, 12, 23, 100, 0, 93, 97]
target_item = 88
indices = find_indices(cricket_scores, target_item)
if indices:
print(f"Item {target_item} found at indices: {indices}")
else:
print(f"Item {target_item} not found in the list")Output:
Item 88 found at indices: [4]
`enumerate` function can be used to find all occurrences of a target item in a list and return their
indices as a list. If no occurrences are found, the function returns an empty list. Using enumerate in Python can be a little difficult, don’t worry we have a detailed article on this. You can check that out and make learning more easy.
If you are also working with data structures like stacks and queues, you may find our guide on Stack vs Queue: Which Is Better for Python? helpful in understanding their differences and applications.”
Conclusion:
Through our journey, we discussed the basic operations of lists in accessing, modifying, and analyzing list items.
Key Takeaways:
index() method: this method quickly locates the first occurrence of the target item. Optional start and end parameters can be used to keep searching within the start and end boundaries.
enumerate() method: Through this method, we simultaneously access both index and data item.
Moreover, it returns all the indices of the target item.
Custom iterate method: By combining index traversal with logical conditions and a `for` loop, we can
perform an afterward operation on that target item.
Also, if you’re interested in sorting algorithms, then you must check out our article on What is QuickSort in Python?, which covers the implementation and working of this efficient sorting technique.
