Introduction to Python
Python is a high-level programming language that is widely used for its simplicity and readability. It is known for its versatility and can be used for various applications such as web development, data analysis, artificial intelligence, and more. One of the key features of Python is its ability to work with lists, which are ordered collections of items. In this article, we will explore how to add items to a list in Python with examples.
Adding Items to a List
In Python, you can add items to a list using various methods. Let’s take a look at some of the commonly used methods:
Method 1: Using the append() Method
The append()
method allows you to add an item to the end of a list. Here’s an example:
fruits = ['apple', 'banana', 'orange']
fruits.append('grape')
print(fruits)
Output:
['apple', 'banana', 'orange', 'grape']
In the above example, the append()
method is used to add the item ‘grape’ to the end of the ‘fruits’ list.
Method 2: Using the insert() Method
The insert()
method allows you to add an item at a specific position in the list. Here’s an example:
fruits = ['apple', 'banana', 'orange']
fruits.insert(1, 'grape')
print(fruits)
Output:
['apple', 'grape', 'banana', 'orange']
In the above example, the insert()
method is used to add the item ‘grape’ at index 1 in the ‘fruits’ list. The existing items are shifted to the right to accommodate the new item.
Method 3: Using the extend() Method
The extend()
method allows you to add multiple items to a list. Here’s an example:
fruits = ['apple', 'banana', 'orange']
more_fruits = ['grape', 'kiwi']
fruits.extend(more_fruits)
print(fruits)
Output:
['apple', 'banana', 'orange', 'grape', 'kiwi']
In the above example, the extend()
method is used to add the items from the ‘more_fruits’ list to the end of the ‘fruits’ list.
Method 4: Using the + Operator
You can also use the + operator to concatenate two lists and create a new list. Here’s an example:
fruits = ['apple', 'banana', 'orange']
more_fruits = ['grape', 'kiwi']
all_fruits = fruits + more_fruits
print(all_fruits)
Output:
['apple', 'banana', 'orange', 'grape', 'kiwi']
In the above example, the + operator is used to concatenate the ‘fruits’ and ‘more_fruits’ lists and create a new list called ‘all_fruits’.
Conclusion
Adding items to a list in Python is a fundamental operation. In this article, we discussed various methods such as append(), insert(), extend(), and the + operator to add items to a list. By understanding these methods, you can easily manipulate lists and build more complex programs in Python.