Append and extend python

Метод append() и extend() в Python

Метод append() в Python добавляет элемент в конец списка.

Параметры

Метод принимает единственный аргумент:

Элементом могут быть числа, строки, словари, другой список и т.д.

Возвращаемое значение

Метод не возвращает никакого значения (возвращает None).

Пример 1: Добавление элемента в список

# animals list animals = ['cat', 'dog', 'rabbit'] # 'guinea pig' is appended to the animals list animals.append('guinea pig') # Updated animals list print('Updated animals list: ', animals)
Updated animals list: ['cat', 'dog', 'rabbit', 'guinea pig']

Пример 2: Добавление списка в список

# animals list animals = ['cat', 'dog', 'rabbit'] # list of wild animals wild_animals = ['tiger', 'fox'] # appending wild_animals list to the animals list animals.append(wild_animals) print('Updated animals list: ', animals)
Updated animals list: ['cat', 'dog', 'rabbit', ['tiger', 'fox']]

Важно отметить, что в список животных в приведенной выше программе добавляется один элемент (список wild_animals).

Если вам нужно добавить элементы списка в другой список (а не в сам список), используйте метод extend().

При этом все элементы Iterable добавляются в конец list1.

Параметры

Как уже упоминалось, метод принимает итерацию, такую как список, кортеж, строка и т.д.

Читайте также:  Loggerfactory class in java

Возвращаемое значение

Метод изменяет исходный список, он не возвращает никакого значения.

Пример 1: Использование метода

# language list language = ['French', 'English'] # another list of language language1 = ['Spanish', 'Portuguese'] # appending language1 elements to language language.extend(language1) print('Language List:', language)
Language List: ['French', 'English', 'Spanish', 'Portuguese']

Пример 2: Добавить элементы кортежа и установить их в список

# language list language = ['French'] # language tuple language_tuple = ('Spanish', 'Portuguese') # language set language_set = # appending language_tuple elements to language language.extend(language_tuple) print('New Language List:', language) # appending language_set elements to language language.extend(language_set) print('Newer Language List:', language)
New Language List: ['French', 'Spanish', 'Portuguese'] Newer Language List: ['French', 'Spanish', 'Portuguese', 'Japanese', 'Chinese']

Другие способы расширения списка

Вы также можете добавить в список все элементы итерации, используя:

a = [1, 2] b = [3, 4] a += b # a = a + b # Output: [1, 2, 3, 4] print('a =', a)

2. Синтаксис нарезки списка.

a = [1, 2] b = [3, 4] a[len(a):] = b # Output: [1, 2, 3, 4] print('a =', a)

Источник

What is the Difference Between Append and Extend in Python List Methods?

Python Certification Course: Master the essentials

You’ve come to the correct place if you’d like to discover how to use append() and extend() and grasp their differences. They are effective list approaches that you will undoubtedly implement in your Python applications. The append() method in the Python programming language adds an item to a list that already exists whereas the extend() method adds each of the iterable elements which is supplied as a parameter to the end of the original list .

Let’s know more about the two functions in more detail.

Extend vs Append Python List Methods

Lists in the programming language Python are mutable (The term mutable means that the programmers can update an element in any given list by retrieving it as a component of the allocation statement), meaning they can be extended or shortened per the programmer’s choice. In other words, programmers can either add or remove elements from specified indices. Append() and extend() are two built-in list functions generally used to add elements, tuples , etc into any given list.

What is Append in Python?

The append() method in the programming language Python adds an item to a list that already exists . Instead of being returned to a new list, the item will be added toward the end of the existing list. Because lists can include elements of several data types, programmers can add items of any data type.

The method is responsible for adding its parameters to the end of a list as a single element. The list’s length grows by one. The original list is updated when the append() method is used. The approach alters the original list in memory rather than creating a copy.

USE OF APPEND

Note: Lists can include items of several data types, you can add items of any data type.

Syntax of Append() Function

Let’s discuss the parameters of the syntax:

  • This is the list that’s going to be changed. Typically, this is a variable that refers to a list.
  • A dot, preceded by the method’s name.
  • append() method
  • The element that needs to be added towards the end of the list is enclosed in parentheses, this is a mandatory parameter.

Keep in Mind: The dot in the syntax of the append() method is quite significant. This is known as «dot notation.» The dot simply indicates «call this function on this specific list,» so the function’s effect will be implemented in the list that comes before the dot.

Let’s go through a few examples to understand the concept of the append method in Python.

Example 1) Adding an element to the list using the append method in Python.

Example 2) Adding a list of elements to the list using the append method in Python.

You may be wondering why the entire list was added as a single item. This is due to the fact that the append() function appends an element as a whole to the list at the end. If the element is a sequence, such as a list, dictionary, or tuple, then the entire sequence will be added to the existing list as one single item .

Example 3) Adding a tuple as an item to the list using the append method in Python.

In this situation, the element to be added is a tuple to the list as a single item rather than as distinct items.

What is Extend in Python?

The extend method in Python is responsible for appending each iterable (it can be a tuple, any string, or a list) member to the list’s end as well as increasing the length of the original list by the count of iterable elements supplied as an argument.

Note: The original list is modified using the extend method.

Let’s go through a few examples.

Example 1) Extending an existing List.

Output of the Code:

Example 2) Extending an existing list by adding several elements one by one to the list.

Output of the code:

Example 3) Extending an existing list by adding strings.

Strings behave differently when using the .extend() function. Since each character in any given string is treated as a «item,» the characters are inserted one by one in the sequence in which they occur in the string.

Extend Vs Append Python Comparative Analysis

The differences between the methods append() and extend() are shown in the tables below:

Append Extend
The argument element given as input is appended to the end of the list. Each iterable element supplied as a parameter is added to the end of the original list.
The list’s length grows by one. The length of the list increases in proportion to the number of items in the iterable.
Append() method has a constant time complexity of O(1) The append() method has a constant time complexity, this is because lists are spontaneously accessed, the very last item can be reached in O(1) time, which is why adding any new item at the end of the list takes O(1) time. Extend() method in Python shows a time complexity equal to O(n) where the variable n demonstrates the size of the iterable since the function has to iterate through the length of the list.
An iterable provided as a parameter appends to the end of the list unchanged as a single entry. When an iterable is provided as an input, every one of its elements is appended to the end of the list.

Comparing Extend and Append in Single Program

Let’s compare the two methods which we have discussed in the article above through one simple program.

Output of the Code:

The output of the extend is such that all the elements are iterable whereas the output of the append method adds the elements as a singular item.

The above program will make it easy for programmers to understand the difference between the two methods extend and append .

Learn More

If you are new to Python and would like to know what Python is and why is it widely used, check out this article What is Python Programming Language?.

Check out this article Applications of Python to know about the various applications of Python in real life.

To know how to install Python in your Windows system, you can check out this article How to Install Python in Windows?

Do you know what lists are in Python? If not, programmers can go through the given article, List in Python which covers the parameters of list in Python as well as examples.

Conclusion

  • We explored the main aspects of Lists in the programming language Python, which are mutable as well as ordered collections of elements, in this article.
  • How to append() as well as extend() to add new elements to an existing list object were also covered in the article.
  • The former method, that is, the append() function is responsible for adding the specified entry to the end of the list by extending its length exactly by one.
  • The latter is responsible for iterating through the provided input, appending each individual member to the list.
  • The append() function in programming language adds one to the length of the original list. This implies that if the added input is a list of items, then the given list will be appended rather than the specific items.

Источник

Оцените статью