วันอาทิตย์ที่ 18 กุมภาพันธ์ พ.ศ. 2567

How does the Python enumerate function work, and what is its significance in iterating over sequences? Provide an example to illustrate its usage.

 Q20: How does the Python enumerate function work, and what is its significance in iterating over sequences? Provide an example to illustrate its usage.

A20:

  • Working of enumerate:

    • The enumerate function in Python is used to iterate over a sequence (such as a list, tuple, or string) while keeping track of the index of each element. It returns pairs of index and element as tuples.
  • Significance in Iterating Over Sequences:

    • enumerate simplifies the process of iterating over sequences by providing both the index and the corresponding element, eliminating the need to manually manage indices.
# Example of using enumerate
fruits = ['apple', 'banana', 'orange']

for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")

Output:

Index: 0, Fruit: apple Index: 1, Fruit: banana Index: 2, Fruit: orange

In this example, enumerate is used to iterate over the fruits list, providing both the index and the corresponding fruit in each iteration.

ไม่มีความคิดเห็น:

แสดงความคิดเห็น

How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be employed to mitigate its effects?

  Q10: How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be emplo...