- Learn Programming in Python with Cody Jackson
- Cody Jackson
- 365字
- 2021-06-10 19:06:10
Adding list elements
Adding new items to a list is extremely easy. You simply tell the list to add them, as shown in the following screenshot. This also demonstrates how any item can be placed in a list, even disparate data types:
The append() method simply adds a single item to the end of a list; it's different from concatenation since it takes a single object and not a list. The append() method changes the list in-place and doesn't create a brand new list object, nor does it return the modified list. To view the changes, you have to expressly call the list object again, as shown in line 3. So be aware of that in case you are confused about whether the changes actually took place.
If you want to put the new item in a specific position in the list, you have to tell the list which position it should be in; that is, you have to use the index of what the position is. This is demonstrated in line 4 of the previous screenshot.
You can add a second list to an existing one by using the extend() method. Essentially, the two lists are concatenated (linked) together, as shown in the following screenshot:
Be aware that there is a distinct difference between extend() and append(). The extend() function takes a single argument, which is always a list, and adds each of the elements of that list to the original list; the two lists are merged into one. The append() function takes one argument, which can be any data type, and simply adds it to the end of the list; you end up with a list that has one element, which is the appended object.
Compare line 10 in the following screenshot to line 8 in the previous screenshot. Whereas appending the new_l list to the original list simply added each item from new_l to the original, essentially increasing the number of elements, when extending the exact same new_l list to the original, the entire list object was added, rather than the individual elements.
- Java完全自學教程
- Java面向?qū)ο蟪绦蜷_發(fā)及實戰(zhàn)
- Mastering Data Mining with Python:Find patterns hidden in your data
- 智能手機APP UI設(shè)計與應(yīng)用任務(wù)教程
- 微信小程序開發(fā)實戰(zhàn):設(shè)計·運營·變現(xiàn)(圖解案例版)
- SQL Server 2008中文版項目教程(第3版)
- Instant Automapper
- Learning Bootstrap 4(Second Edition)
- MongoDB Administrator’s Guide
- H5頁面設(shè)計與制作(全彩慕課版·第2版)
- GO語言編程從入門到實踐
- 軟件自動化測試實戰(zhàn)解析:基于Python3編程語言
- Implementing OpenShift
- 高性能Java架構(gòu):核心原理與案例實戰(zhàn)
- Mastering Android NDK