Lists in Python are ordered, mutable collections of items enclosed in square brackets [] . They are versatile and widely used for storing and managing various data types. Here's a breakdown with examples: Creating Lists: Python # Empty list my_list = [] # List with elements fruits = [ "apple" , "banana" , "orange" ] # List with different data types mixed_list = [ 10 , "hello" , 3.14 , True ] Accessing Elements: Indexing: Use numerical positions starting from 0. Python first_fruit = fruits[ 0 ] # "apple" last_fruit = fruits[- 1 ] # "orange" Slicing: Extract a sublist using start, stop, and step (optional) indices. Python first_two_fruits = fruits[: 2 ] # ["apple", "banana"] last_two_fruits = fruits[- 2 :] # ["banana", "orange"] every_other_fruit = fruits[:: 2 ] # ["apple", "orange"] Modifying Lists: Assignment: Change values at specific in...
Searching is a fundamental task in Python, and there are several ways to find an element within a collection or data structure based on specific criteria. Here are some common approaches: 1. Linear Search: This is the simplest method, iterating through each element in the collection and comparing it to the target value. It's suitable for small datasets but becomes inefficient for larger ones due to its O(n) time complexity. Example: Python def linear_search ( data, target ): for i, item in enumerate (data): if item == target: return i return - 1 data = [ 1 , 5 , 8 , 3 , 9 ] target = 8 index = linear_search(data, target) if index != - 1 : print( f"Found {target} at index {index} " ) else : print( f" {target} not found in the data" ) 2. Binary Search: This method only works on sorted data. It repeatedly halves the search space by comparing the target value to the middle element. It has a much better time complex...