Page 70 - Touhpad Ai
P. 70

In order to access an element in a list we need to use index operator [].
                 fruits = ["kiwi", "pineapple", "cherry", "orange"]
                 # Accessing elements using positive indexing
                 print(fruits[0])  # Output: kiwi
                 print(fruits[1])  # Output: pineapple
                 # Accessing elements using negative indexing
                 print(fruits[-1])  # Output: orange

                 print(fruits[-2])  # Output: cherry
              Lists are mutable, so you can change their elements. Just specify the index value with the new element to be added.

                 fruits[1] = "blueberry"
                 print(fruits)  # Output: ['kiwi', 'blueberry', 'cherry', 'orange']

              Adding Elements
              You can add elements to a list by using the append(), insert(), and extend() methods.
              Using append() Function
              You  can only add  one element at a time  with  append(). If  you  want to  add  multiple  elements  using  append(),
              you need to use loops. Tuples can also be added to a list using append() because tuples cannot be changed after they're
              created. Unlike sets, you can add lists to an existing list using the append() function.

                 # Adding elements using append() function
                 fruits.append("strawberry")
                 print(fruits)
                 Output:
                 ['kiwi', 'blueberry', 'cherry', 'orange', 'strawberry']
              Using insert() Function
              The append() function adds an element only to the end of a list. To add an element at a specific position, you need to
              use the insert() function. Unlike append(), which takes only one argument (the value to add), insert() requires
              two arguments: the position where you want to insert the element and the value itself.
                 fruits.insert(2, "banana")
                 print(fruits)
                 Output:

                 ['kiwi', 'blueberry', 'banana', 'cherry', 'orange', 'strawberry']
              Using extend() Function

              The extend() method is used to add multiple elements to the end of a list at the same time.
                 # Adding elements using extend() function
                 fruits1=['apple', 'mango']
                 fruits.extend(fruits1)
                 print(fruits)

                 Output:
                 ['kiwi', 'blueberry', 'banana', 'cherry', 'orange', 'strawberry', 'apple', 'mango']

              Removing List Elements

              You can remove elements from the list by using remove and pop functions.




                 68     Touchpad Artificial Intelligence - XI
   65   66   67   68   69   70   71   72   73   74   75