📜  python push to list - Python (1)

📅  最后修改于: 2023-12-03 15:34:03.827000             🧑  作者: Mango

Python Push to List

In Python, lists are mutable data structures that can contain a collection of values of different data types. One way to add an element to a list is by using the append() method. This method adds a single value to the end of the list.

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # Output: [1, 2, 3, 4]

Another way to add elements to a list is by using the extend() method or the + operator. The extend() method adds all the elements of an iterable to the end of a list, while the + operator concatenates two lists.

my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list)  # Output: [1, 2, 3, 4, 5]

my_list = [1, 2, 3]
new_list = my_list + [4, 5]
print(new_list)  # Output: [1, 2, 3, 4, 5]

We can also insert a new element at a specific index of a list using the insert() method.

my_list = [1, 2, 3]
my_list.insert(1, 'a')
print(my_list)  # Output: [1, 'a', 2, 3]

Furthermore, we can use list comprehension to create a new list based on an existing list and a condition.

my_list = [1, 2, 3, 4, 5]
new_list = [x for x in my_list if x % 2 == 0]
print(new_list)  # Output: [2, 4]

In conclusion, Python provides several methods for adding elements to a list. Choose the method that fits your requirements and use it to push your data to the list.