Page 444 - ComputerScience_Class_11
P. 444

Difference between List[] and Tuple()
              Here are the differences between List and Tuple in Python:

                      Features                      List [ ]                                Tuple ( )
                  Definition       A sequence data type that is mutable     A sequence data type that is immutable
                  Mutability       Elements can be changed, added or removed  Elements cannot be changed after creation
                  Syntax           Uses square brackets [ ]                 Uses parentheses ( )

                  Speed            Slower compared to tuple                 Faster than list
                  Memory Usage     Uses more memory                         Uses less memory
                  Usage            Used when data needs modification        Used for fixed or read-only data
                  Example          a = [1, 2, 3]                            b = (1, 2, 3)


              Importance of Tuple over List
              Tuples have some advantages over lists in Python.
              •  Safety: A tuple cannot be modified after creation, which helps prevent accidental changes to the data.

              •  Speed: Since tuples are immutable, Python can process them faster than lists.
              •  Memory Efficient: Tuples consume less memory compared to lists.

              Accessing Different Elements in a Tuple
              Tuple elements cannot be changed, but they can be accessed using their index number.

              Program 11: To access elements stored in a tuple variable.
                   Program 11.py

                File  Edit  Format   Run   Options   Window    Help

                # Creating a tuple of birds
                birds = ("Eagle", "Sparrow", "Owl")
                # Accessing element at index 0
                print("Element at index 0", birds[0])
                # Accessing element at index 1
                print("Element at index 1", birds[1])
                # Accessing element at index 2
                print("Element at index 2", birds[2])




                   Output

                Element at index 0 Eagle
                Element at index 1 Sparrow
                Element at index 2 Owl




              12.4.4 Characteristics of Sequence data types in Python
              There are some characteristics of Sequence data types in Python:
              •  Collection of Elements: Sequence data types store multiple items in a single variable.

              •  Position-Based Access: Elements are accessed using their position (index number).



                  442  Touchpad Computer Science (Ver. 3.0)-XI
   439   440   441   442   443   444   445   446   447   448   449