官术网_书友最值得收藏!

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:

Appending to a list

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:

Extending a list with another list

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.

extend() versus append()
主站蜘蛛池模板: 隆昌县| 蚌埠市| 大邑县| 温泉县| 永寿县| 洪泽县| 吴忠市| 墨玉县| 长丰县| 凤台县| 定陶县| 泽库县| 南靖县| 名山县| 忻州市| 桂林市| 柯坪县| 南投市| 绍兴县| 仙桃市| 镇远县| 宁夏| 汶川县| 甘谷县| 尚志市| 连城县| 阿巴嘎旗| 南皮县| 饶河县| 新乐市| 班戈县| 遵义县| 诸城市| 洪湖市| 绍兴县| 新竹县| 米易县| 宁河县| 云南省| 正蓝旗| 凤山市|