在Python中,`append()`方法用于在列表的末尾添加一个新的元素。以下是`append()`方法的基本用法:
基本语法
list.append(obj)
`list` 是要操作的列表对象。
`obj` 是要添加到列表末尾的对象。
使用示例
添加整数
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
print(numbers) 输出: [1, 2, 3, 4, 5, 6]
添加字符串
fruits = ['apple', 'banana', 'orange']
fruits.append('watermelon')
print(fruits) 输出: ['apple', 'banana', 'orange', 'watermelon']
添加列表
a = [1, 2, 3]
a.append(5)
print(a) 输出: [1, 2, 3, 5]
a = [1, 2, 3]
a.append()
print(a) 输出: [1, 2, 3, ]
注意事项
`append()`方法只能用于列表对象,不能用于其他类型的对象。
`append()`方法会直接修改原列表,而不会返回一个新的列表。
当添加列表时,`append()`会将整个列表作为一个单独的对象添加到原列表的末尾,而不是列表中的每个元素。
希望这能帮助你理解Python中`append()`方法的用法