learn how to add to an empty list in python

Adding elements to an empty list in Python is a basic operation. To get started, you first create an empty list by assigning an empty pair of square brackets [] to a variable, like this:

my_list = []

Then, add an item to the list using .append():

my_list.append("new item")

Adding String Elements

To add elements to an empty list in Python, you can follow these steps:

1.Start by creating an empty list, for example, fruits = [].

2.Use the .append() method to add elements to the list one at a time. For instance, you can add “Apple” by using fruits.append(“Apple”), and then add “Banana” with fruits.append(“Banana”).

# Creating an empty list
fruits = []

# Adding string elements to the list
fruits.append("Apple")
fruits.append("Banana")

print(fruits)
# After these operations ["Apple", "Banana"]

Adding Different Types of Elements

To create a mixed list with different types of elements in Python, you can follow these steps:

1.Start with an empty list, for example, mixed_list = [].

2.Use the .append() method to add elements of different types to the list. For instance, you can add an integer (e.g., mixed_list.append(10)), a float (e.g., mixed_list.append(3.14)), a string (e.g., mixed_list.append(“Python”)), and even another list (e.g., mixed_list.append([1, 2, 3])).

As a result, mixed_list will become a collection of diverse elements: [10, 3.14, “Python”, [1, 2, 3]].

# Creating an empty list
mixed_list = []

# Adding different types of elements
mixed_list.append(10)     # Adding an integer
mixed_list.append(3.14)    # Adding a float
mixed_list.append("Python")  # Adding a string
mixed_list.append([1, 2, 3]) # Adding another list
# After these operations [10, 3.14, "Python", [1, 2, 3]]

Leave a Reply

Your email address will not be published. Required fields are marked *