Python append element to list python

Python — Add List Items

To add an item to the end of the list, use the append() method:

Example

Using the append() method to append an item:

Insert Items

To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Example

Insert an item as the second position:

Note: As a result of the examples above, the lists will now contain 4 items.

Extend List

To append elements from another list to the current list, use the extend() method.

Example

Add the elements of tropical to thislist :

thislist = [«apple», «banana», «cherry»]
tropical = [«mango», «pineapple», «papaya»]
thislist.extend(tropical)
print(thislist)

The elements will be added to the end of the list.

Add Any Iterable

The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).

Example

Add elements of a tuple to a list:

thislist = [«apple», «banana», «cherry»]
thistuple = («kiwi», «orange»)
thislist.extend(thistuple)
print(thislist)

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

How To add Elements to a List in Python

How To add Elements to a List in Python

In this tutorial, we will learn different ways to add elements to a list in Python.

There are four methods to add elements to a List in Python.

  1. append() : append the element to the end of the list.
  2. insert() : inserts the element before the given index.
  3. extend() : extends the list by appending elements from the iterable.
  4. List Concatenation: We can use the + operator to concatenate multiple lists and create a new list.

Prerequisites

In order to complete this tutorial, you will need:

This tutorial was tested with Python 3.9.6.

append()

This function adds a single element to the end of the list.

fruit_list = ["Apple", "Banana"] print(f'Current Fruits List fruit_list>') new_fruit = input("Please enter a fruit name:\n") fruit_list.append(new_fruit) print(f'Updated Fruits List fruit_list>') 
Current Fruits List ['Apple', 'Banana'] Please enter a fruit name: Orange Updated Fruits List ['Apple', 'Banana', 'Orange'] 

This example added Orange to the end of the list.

insert()

This function adds an element at the given index of the list.

num_list = [1, 2, 3, 4, 5] print(f'Current Numbers List num_list>') num = int(input("Please enter a number to add to list:\n")) index = int(input(f'Please enter the index between 0 and len(num_list) - 1> to add the number:\n')) num_list.insert(index, num) print(f'Updated Numbers List num_list>') 
Current Numbers List [1, 2, 3, 4, 5] Please enter a number to add to list: 20 Please enter the index between 0 and 4 to add the number: 2 Updated Numbers List [1, 2, 20, 3, 4, 5] 

This example added 20 at the index of 2 . 20 has been inserted into the list at this index.

extend()

This function adds iterable elements to the list.

extend_list = [] extend_list.extend([1, 2]) # extending list elements print(extend_list) extend_list.extend((3, 4)) # extending tuple elements print(extend_list) extend_list.extend("ABC") # extending string elements print(extend_list) 
[1, 2] [1, 2, 3, 4] [1, 2, 3, 4, 'A', 'B', 'C'] 

This example added a list of [1, 2] . Then it added a tuple of (3, 4) . And then it added a string of ABC .

List Concatenation

If you have to concatenate multiple lists, you can use the + operator. This will create a new list, and the original lists will remain unchanged.

evens = [2, 4, 6] odds = [1, 3, 5] nums = odds + evens print(nums) # [1, 3, 5, 2, 4, 6] 

This example added the list of evens to the end of the list of odds . The new list will contain elements from the list from left to right. It’s similar to the string concatenation in Python.

Conclusion

Python provides multiple ways to add elements to a list. We can append an element at the end of the list, and insert an element at the given index. We can also add a list to another list. If you want to concatenate multiple lists, then use the overloaded + operator

Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers — for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!

Источник

4 Ways to Add Elements to a List in Python (Theory & Examples)

To add elements to a list in Python, use the append() method:

nums = [1, 2, 3] nums.append(4) print(nums)

To add multiple elements to a list, use the built-in extend() method:

nums = [1, 2, 3] nums.extend([4, 5, 6]) print(nums)

This is a comprehensive guide to adding to lists in Python. Besides the quick answer above, you’ll learn different methods of how to add values to a list.

Let’s jump into it!

Adding Elements to a List in Python

There are four main ways to add elements to a list in Python:

Let’s take a closer look at how each method works.

1. Append() Method—Add an Element to the End of a List

Python list append method adds an element to the end of the list

A popular way to add an element to a list is using the built-in append() method. It takes a single element as its argument and adds it to the end of the list. This method is useful as most of the time you want to add elements to the end of the list — just like this method does.

For example, let’s add a fifth number to the end of a list of four numbers:

nums = [1, 2, 3, 4] nums.append(5) print(nums)

If you wish to add multiple items to the end of the list, use the extend() method. You’ll learn about this method in just a bit.

2. Insert() Method—Add an Element to a Specific Index of a List

Python list insert method adds a value to a specific index of the list

To add an element at a specific position in the list, use the Python list’s built-in insert() method.

This method takes an index and an element as its arguments. The index shows at which position you want to add the element to the list.

For example, let’s add the number 10 as the first element in a list of numbers:

nums = [1,2,3] nums.insert(0,10) print(nums)

3. Extend() Method—Add Multiple Items to a List

Python list extends adds a list of values to the end of a list

Sometimes you need to add multiple values to the end of a list in the same go.

In this case, you can use the built-in extend() method. It works similarly to the append() method, but it takes a list as an argument and adds each element to the end of the list.

nums = [1,2,3] nums.extend([10, 20, 30]) print(nums)

Feel free to check a thorough comparison between the append() and extend() methods.

4. List Merging with the + Operator in Python

The + operator adds values to the end of a Python list

To merge two or more lists together, you can also use the + operator. This takes the list on the left-hand side and adds the element of the list on the right-hand side to it. Notice that this operator doesn’t directly modify either of the lists. Instead, it creates a new one.

nums1 = [1, 2, 3] nums2 = [4, 5, 6] result = nums1 + nums2 print(result)

Another example of merging more than two lists:

nums1 = [1, 2, 3] nums2 = [4, 5, 6] nums3 = [7, 8, 9] result = nums1 + nums2 + nums3 print(result)

If you want to modify the original list when adding values with the + operator, use the += operator instead.

nums = [1,2,3] more_nums = [4,5,6] nums += more_nums print(nums)

Conclusion

In Python, there are four ways to add elements to a list.

  1. Add a single element to the end with append() method.
  2. Add a single element to a specific index with insert() method.
  3. Add multiple elements to the end of the list using the extend() method
  4. Merge lists with the + operator.

Thanks for reading. I hope you enjoyed it.

Further Reading

Источник

Читайте также:  Python create dataframe name
Оцените статью