我如何在python中创建列表和添加元素?

问题描述 投票:0回答:1

我添加了以下可读的代码,用于创建一个 "列表 "和所有添加元素的方法。下面是代码。

创建列表。使用append(),insert()添加元素。

# Create lists
list1 = [1,4,6,8] # integer list.
list2 = [] # Empty List.
list3 = [1.2,'Raj',1] # mixed list.

# Print Created lists
print(list1)
print(list2)
print(list3)

# Add element using append(). Elements will be added at the last of list.
list1.append(11)
list1.append(12)
print(list1)

# Add elements in an empty list using for loop and append()
list2 = []
string = 'abcdef'
for ele in string:
list2.append(ele)
print(list2)

# Add element using insert(). Element will add at any position using index
list4 = ['r','j','s','h']
list4.insert(1,'a')
list4.insert(3,'e')
print(list4)
python-3.x list collections insert append
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.