Searching in List in Hindi – Python

Searching का मतलब है list में किसी विशेष element को ढूंढना। Python में searching के लिए कुछ सामान्य तरीके हैं। जिनके बारें में नीचे दिया गया है:-

1:- in Keyword

Python का in कीवर्ड यह check करता है कि कोई element लिस्ट में मौजूद है या नहीं।

# Example: Searching using 'in'

fruits = ['apple', 'banana', 'cherry']

if 'banana' in fruits:

    print("Banana is present in the list.")

else:

    print("Banana is not in the list.")

2:- index() Method

index() मेथड list में दिए गए element का पहला position (index) बताता है। अगर element लिस्ट में नहीं है, तो यह error दिखाता है।

# Example: Using index()

colors = ['red', 'green', 'blue', 'yellow']

try:

    position = colors.index('blue')

    print("'blue' is found at index:", position)

except ValueError:

    print("'blue' is not in the list.")

3:- Linear Search

Linear search एक सरल searching तकनीक है इसमें list के हर element को एक क्रम (sequence) में एक-एक करके check किया जाता है।

इसमें अगर element मिल जाता है, तो उसकी position को return कर दिया जाता है। अगर पूरा लिस्ट check करने के बाद भी element नहीं मिलता, तो बताया जाता है कि element लिस्ट में मौजूद नहीं है।

नीचे इसका example दिया गया है:-

# Example: Linear Search

def linear_search(lst, target):

    for i in range(len(lst)):

        if lst[i] == target:

            return i

    return -1

numbers = [10, 20, 30, 40, 50]

target = 30

result = linear_search(numbers, target)

if result != -1:

    print(f"Element found at index {result}.")

else:

    print("Element not found.")

4:- Binary Search

Binary search एक प्रभावी searching तकनीक है जिसका उपयोग sorted list में किया जाता है। यह divide-and-conquer तकनीक पर काम करता है, जहां list को दो हिस्सों में divide किया जाता है।

बाइनरी सर्च sorted list में element को ढूंढने का सबसे तेज़ तरीका है। इसका example नीचे दिया है:-

# Example: Binary Search

def binary_search(lst, target):

    low, high = 0, len(lst) - 1

    while low <= high:

        mid = (low + high) // 2

        if lst[mid] == target:

            return mid

        elif lst[mid] < target:

            low = mid + 1

        else:

            high = mid - 1

    return -1

sorted_numbers = [10, 20, 30, 40, 50]

target = 40

result = binary_search(sorted_numbers, target)

if result != -1:

    print(f"Element found at index {result}.")

else:

    print("Element not found.")

इसे पढ़ें:-

Leave a Comment