Python add in example

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.

Источник

How to Add Elements in List in Python?

Python Certification Course: Master the essentials

In Python, a list is a dynamic array that can hold both homogeneous (all items of the same data type) and heterogeneous (items of different data types) data. The data stored in the list is arranged in order and identified by a unique number or position named index.

List in Python language

In the above image, we can see that every element from the list fruits can be accessed by a unique index that starts from 0 .

A list provides several built-in functions that can be used to execute a wide range of operations on data stored in it. Append(), extend(), insert(), sort(), remove(), pop() and many other methods can be used to operate on lists in Python.

In this tutorial, we will learn how to add elements to a list in Python using built-in functions. According to the requirements, the different ways to add elements to lists are explained here.

Python Adds Elements to List Examples

As mentioned earlier, a list in Python is a dynamic array, meaning that you can easily add new elements. You can add an element at any desired position or at the end of the list.

The add(), insert() , and extend() methods in Python are used to add elements to a list. We can add elements to a list using the + operator in Python with these methods.

Methods to add elements in List in Python:

Sr. no Methods Description
1. append() Append method adds the object at the end of the list.
2. insert() Insert method adds the object at the specified index.
3. extend() Extend method appends elements from other iterables in python, like tuples, to the list.
4. List concatenation + operator is used to concatenate multiple lists and create a new list.
5. Slicing Adding another list or tuple using slice() .

In the following section of this article, we will see all these methods regarding adding elements to a list in python.

Add an Item to the End: append()

append() method is used to add elements to the end of the list.

In this code, students.append() adds new element at the end of the original list students

Append takes only one argument, but we can add another list, heterogeneous elements, or tuples using append() .

Above code illustrates how we can add lists, tuples, and elements with other data-type using the append() method.

Insert an Item at Specified Index: insert()

This method adds an element to the specified position on the list. The index of the list is used to specify the position where new elements are to be added.

Note: The index of the list in python starts from 0 . The negative values like -1 mean one position before the end.

Here, in firts case, we can see that word.insert(3, «dog») inserts the string «dog» at 3rd index position. In the second case, words.insert(-2, «cricket») inserts the string «cricket» at 2nd index position from the end, the starting index from end being -0 .

Combine Lists: extend(), + operator

We can add elements of one list to another using the extend() method and + operator. The extend() method and + operator is used to concatenate/combine one list into another.

extend() Method:

extend() method combines all elements of a list or tuple to the end of the original list.

The range() function returns a sequence of numbers, starting from 0 by default, increments by 1 (by default), and stops before a specified number. list(range(5)) is used to create a list of the first five numbers. extend() function is used to add elements from a list to an existing list.

When a string is given as an argument to the extend() method, the string is split into its characters, and each character of the string is added to the original list one by one.

Let’s an example of the same.

In this code list2.extend(«Hello!») is used to add elements of string in the existing list. extend() method splits the string into characters and adds these characters to the existing list one by one.

List Concatenation using + operator:

We can combine elements of two lists in a single new list i.e. concatenate two lists using the + operator.

Let’s see an example of adding elements in List in python using the + operator.

In the above code, lists even_numbers and odd_numbers are concatenated, and the results are displayed in a new list numbers using the + operator.

We can one list into the existing list with the help of += operators.

Here, the existing list fruits is appended with the elements of the new list fruits_new using += . Operators += concatenates two lists, but it gives the result in the existing original string.

Adding Another List or Tuple in the Existing List Using slice()

Slicing in python: Python slice() function returns slice object. [start:end: step] is the syntax used to do slicing of any sequence in python. It returns a sliced object containing elements in the given range only. It takes starting index and ending index as arguments.

For eg., list[2:5] means to return the slice of the list starting from index 2 and ending at index 5.

Note: Ending index is not inclusive in slice(). It means the element at the ending index will not be included in the output.

Now let’s see how to add elements in list in python using slicing.

In this code, numlist[1:1] adds the elements from the given list in the specified position, i.e., starting from 1 and ending at 1.

We can replace the original element in the list if we change the ending index in the slicing. It will replace the original elements with the new elements in the specified index range. Let’s understand this with the help of an example.

In the above code, we can see that code block numlist[1:2] adds the new elements in the original list starting from index position one, but it replaces the elements at the 2nd index position in the num_list.

Conclusion

  • Elements can be added to the list using built-in functions like append(), insert() .
  • append() adds the elements at the end of the list, while insert() adds the element at the specified position.
  • extend() function and + operator is used to concatenate elements from one list/tuple into the other.
  • Slicing can be used to add a sequence of elements to the existing list.
  • Tuples in Python.
  • replace() method in python .

Источник

Читайте также:  Test loc index php
Оцените статью