Adding An Item to a List
Python has a ton of ways of adding items to lists. For example, there’s the popular append() method. Here are the others.
Python: 3.0    Anurag Rana    09 Jul 2021   0
Login to upvote
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Statically defined list
my_list = [2, 5, 6]

# Appending using slice assignment
my_list[len(my_list):] = [5]  # [2, 5, 6, 5]

# Appending using append()
my_list.append(9)  # [2, 5, 6, 5, 9]

# Appending using extend()
my_list.extend([-4])  # [2, 5, 6, 5, 9, -4]

# Appending using insert()
my_list.insert(len(my_list), 3)  # [2, 5, 6, 5, 9, -4, 3]
Copy | Download as: .py file   PNG
Share on: FB   Twitter   LinkedIn   WA
©2021 - code108labs   Contributors   Hosted on DigitalOcean   Partner website: pythoncircle.com