Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 136 - 2615_KEC
P. 136

    In Python, tuples support both positive indexing and negative indexing, similar to lists. Let us
                      understand the positive and negative indexing:

                          Positive indexing starts from 0 for the first element, 1 for the second and so on.

                           Negative indexing allows you to count from the end of the tuple, with -1 being the last element,
                          -2 the second last and so on.

                      Program 3: A program to access elements of a tuple using positive indexing.

                          Program3.py
                       File  Edit  Format   Run    Options   Window    Help

                       week_days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
                       print(week_days[0])  # Access the first element
                       print(week_days[2])  # Access the third element

                          Output
                       Monday
                       Wednesday

                      Program 4: A program to access elements of a tuple using negative indexing.

                          Program4.py

                       File  Edit  Format   Run    Options   Window    Help

                       week_days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
                       print(week_days[-1])  # Access the last element
                       print(week_days[-2])  # Access the second last element

                          Output

                       Friday
                       Thursday

                      IMMUTABILITY OF TUPLES
                      Tuples in Python are immutable, which means once a tuple is created, you cannot modify, add

                      or remove any of its elements.

                      134   Premium Edition-VIII

| 131 132 133 134 135 136 137 138 139 140 141 |