1. <source id="nejs2"></source>
  2. <video id="nejs2"></video>
    <source id="nejs2"></source>
          1. 首頁 > Python 筆記 > 如何在列表中追加元素

            如何在列表中追加元素

            更新:

            Python 提供了向列表追加或添加元素的內置方法。我們也可以將一個列表附加到另一個列表中。下面給出了這些方法。

            • 追加(elmt) - 它在列表末尾追加值。
            • 插入(index,elmt) - 它在指定的索引位置插入值。
            • 擴展(可迭代)- 通過添加可迭代對象擴展列表。

            讓我們通過下面的例子來理解這些方法。

            1.附錄(ELT)

            該函數用于在列表末尾添加元素。下面給出了例子。

            示例-

            
            names = ["Joseph", "Peter", "Cook", "Tim"]
            
            print('Current names List is:', names)
            
            new_name = input("Please enter a name:\n")
            names.append(new_name)  # Using the append() function
            
            print('Updated name List is:', names)
            

            輸出:

            Current names List is: ['Joseph', 'Peter', 'Cook', 'Tim']
            Please enter a name:
            Devansh
            Updated name List is: ['Joseph', 'Peter', 'Cook', 'Tim', 'Devansh']
            

            2.插入(索引,elmt)

            函數的作用是:在給定的索引位置添加元素。當我們想要在特定位置插入元素時,這是有益的。下面給出了例子。

            示例-

            
            list1 = [10, 20, 30, 40, 50]
            
            print('Current Numbers List: ', list1)
            
            el = list1.insert(3, 77)
            print("The new list is: ",list1)
            
            n = int(input("enter a number to add to list:\n"))
            
            index = int(input('enter the index to add the number:\n'))
            
            list1.insert(index, n)
            
            print('Updated Numbers List:', list1)
            

            輸出:

            Current Numbers List:  [10, 20, 30, 40, 50]
            The new list is:  [10, 20, 30, 77, 40, 50]
            enter a number to add to list:
             45
            enter the index to add the number:
            1
            Updated Numbers List: [10, 45, 20, 30, 77, 40, 50]
            

            3.擴展(可迭代)

            extends()函數用于將可迭代元素添加到列表中。它接受可迭代對象作為參數。下面是添加可迭代元素的示例。

            示例-

            
            list1 = [10,20,30]
            list1.extend(["52.10", "43.12" ])  # extending list elements
            print(list1)
            list1.extend((40, 30))  # extending tuple elements
            print(list1)
            list1.extend("Apple")  # extending string elements
            print(list1)
            

            輸出:

            [10, 20, 30, '52.10', '43.12']
            [10, 20, 30, '52.10', '43.12', 40, 30]
            [10, 20, 30, '52.10', '43.12', 40, 30, 'A', 'p', 'p', 'l', 'e']
            

            文章目錄
            頂部 久久久久99精品成人片毛片_黃色A片三級三級三級无码_日本不卡高清视频v中文字幕_高清欧美视频一区二区
            1. <source id="nejs2"></source>
            2. <video id="nejs2"></video>
              <source id="nejs2"></source>