Adding element to list python

Python : How to add an element in list ? | append() vs extend()

In this article we will discuss how to add element in an existing list using different techniques.

Adding item in list using list.append()

It adds the item at the end of list.

For example, we have a list of string i.e.

# List of string wordList = ['hi', 'hello', 'this', 'that', 'is', 'of']

Now let’s add an element at the end of this list using append() i.e.

Frequently Asked:

''' Adding item in list using list.append() ''' wordList.append("from")
['hi', 'hello', 'this', 'that', 'is', 'of', 'from']

Passing an another list as a parameter in list.append()

As list can contain different kind of elements, so if we pass an another list object as parameter in append() i.e.

''' Passing an another list as a parameter in list.append() ''' wordList.append(["one", "use", "data"])

Then whole list object will be added to the end of list. So, list contents will be now,

['hi', 'hello', 'this', 'that', 'is', 'of', 'from', ['one', 'use', 'data']]

Adding all elements of one list to another using list.extend()

It will add all elements of list1 at the end of list. Basically it will merge the two lists i.e.

wordList = ['hi', 'hello', 'this', 'that', 'is', 'of'] ''' Adding all elements of one list to another using list.extend() ''' wordList.extend(["one", "use", "data"])

Now list contents will be,

['hi', 'hello', 'this', 'that', 'is', 'of', 'one', 'use', 'data']

list append() vs extend()

list.append(item) , considers the parameter item as an individual object and add that object in the end of list. Even if given item is an another list, still it will be added to the end of list as individual object i.e.

wordList = ['hi', 'hello', 'this', 'that', 'is', 'of'] wordList.append(["one", "use", "data"])
['hi', 'hello', 'this', 'that', 'is', 'of', ['one', 'use', 'data']]

list.extend(item) , considers parameter item to be an another list and add all the individual elements of the list to the existing list i.e.

wordList = ['hi', 'hello', 'this', 'that', 'is', 'of'] wordList.extend(["one", "use", "data"])
['hi', 'hello', 'this', 'that', 'is', 'of', 'one', 'use', 'data']

Complete example is as follows,

""" Python : How to add element in list | append() vs extend() """ def main(): # List of string wordList = ['hi', 'hello', 'this', 'that', 'is', 'of'] # print the List print(wordList) ''' Adding item in list using list.append() ''' wordList.append("from") # print the List print(wordList) ''' Passing an another list as a parameter in list.append() ''' wordList.append(["one", "use", "data"]) # print the List print(wordList) wordList = ['hi', 'hello', 'this', 'that', 'is', 'of'] ''' Adding all elements of one list to another using list.extend() ''' wordList.extend(["one", "use", "data"]) # print the List print(wordList) if __name__ == "__main__": main()
['hi', 'hello', 'this', 'that', 'is', 'of'] ['hi', 'hello', 'this', 'that', 'is', 'of', 'from'] ['hi', 'hello', 'this', 'that', 'is', 'of', 'from', ['one', 'use', 'data']] ['hi', 'hello', 'this', 'that', 'is', 'of', 'one', 'use', 'data']

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

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!

Источник

Читайте также:  Php variable not defined
Оцените статью