Python list append first

Add Element to Front of List in Python

How to add elements to the front of the list in Python? You can add an element to the start or front of a list by using the + operator, insert() , slicing , unpacking operator , collections.deque.appendleft() , and extend() function. In this article, I will explain adding elements to front a list in python by using all these methods with examples.

Читайте также:  Получить элемент html страницы

1. Quick Examples of Adding Items to the Front of a List

If you are in a hurry, below are some quick examples of adding elements to the front of a list in python.

2. Add Element to Front of List Using insert()

You can use the list.insert() to add an element to the front of a list in Python, all you need to do is just pass the 0 as the first argument and the value you wanted to add as a second param. This method is used to add an element by index to python list. For example, the below code adds the ‘ Python’ at the first position on the list.

This example yields the below output.

Python List Add to Front

3. Add Element to Front of List Using + Operator

You can use the «+» operator to concatenate two lists together. Use the element you wanted to add as a left operand within square brackets.

4. Using Iterable Unpacking Operator

Alternatively, you can use the iterable unpacking operator to add an element to the front of a Python list. Here, create a new list that includes the element followed by the elements of the original list. For example,

5. Add Element to Front of List Using Slicing

You can use slicing to insert an element at the front of a list by assigning the result of slicing to a new list that includes the element. You can assign the [:0] sliced lists to the list converted from the element.

6. Add Element to Front of List Using extend() Method

Similarly, you can add an element to the front of a list using the extend() method, you can create a new list that includes the element and then extend the original list with the new list. By using this you can also join multiple Python lists.

7. Using collections.deque.appendleft() Method

The collections.deque.appendleft() method can be used to add an element to the front of a list-like object by creating a deque and using the appendleft() method to insert the element at the left end of the deque.

Conclusion

In this article, I have explained how to add an element to the front of a list in python by using the + operator, insert() , slicing , unpacking operator , collections.deque.appendleft() , and extend() functions with examples.

You may also like reading:

Источник

8 ways to add an element to the beginning of a list and string in Python

Let’s look at different methods for adding elements to the beginning of a list and string: concatenation, insert, append, extend, rjust, and f-strings.

How to add an item to the top of a Python list: 4 methods

Lists in Python are mutable and ordered data structures designed to store a group of values. If you need to insert an element in the first position of an existing list during the program execution, you can use one of the methods described below.

Method 1: insert

This method is implemented using the built-in insert() method of lists. This method works with any type of data and allows you to insert the desired element at any position in the existing list, including the first one. The insert() method takes two parameters – the index (position) at which the element is to be inserted, and the element itself. Counting positions in Python starts from zero – Accordingly, to insert an element at the beginning of the list , you need to specify 0 , and not, as the first parameter 1 . Let’s take an example. Suppose we have a list [1, 2, 3] where we want to insert the number 5 at the beginning. Use the insert() method:

arr = [1, 2, 3] arr.insert(0, 5) print(arr) 

Источник

Python list append first

С помощью конкатенации (сложения) тоже можно вставить нужный элемент в начало списка. Правда, для этого нужно, чтобы элемент был представлен в виде списка:

Результат будет таким же, как и в первом способе:

Способ 3: метод append

Этот метод по умолчанию расширяет существующий список, добавляя элемент в конец. Но ничто не мешает расширить список, состоящий из единственного элемента:

sp = [1, 2, 3] num = [5] num.append(sp) print(num) 

Результат при использовании append() отличается – получится вложенный список:

Нужный элемент, однако, получает индекс 0 , так что цель достигнута. Кроме того, при решении некоторых задач может потребоваться создание именно вложенного списка, поэтому способ имеет право на жизнь.

Способ 4: метод extend

Метод extend() похож на append() – с той разницей, что он сохраняет «одномерность» списка:

sp = [1, 2, 3] num = [5] num.extend(sp) print(num) 

Результат – обычный, не вложенный, список:

Отметим, что одномерность сохранится даже в том случае, если элемент, который нужно поставить в начало списка, сам является списком, состоящим из нескольких элементов:

sp = [1, 2, 3] num = [5, 6, 7] num.extend(sp) print(num) 

4 способа добавления элемента в начало строки в Python

Строки в Python относятся к неизменяемому типу данных str , и представляют собой последовательности различных символов. Поскольку строки не изменяются, добавить элементы в начало последовательности можно только путем создания новой строки.

Способ 1: конкатенация

Строки в Python можно соединять (результатом будет новая строка). Рассмотрим на примере вставки знака + в начало строки, содержащей абстрактный мобильный номер:

el = '+' num = '91956612345' print(el + num) 

Результатом операции станет новая строка:

Способ 2: использование f-строки

Вставить элемент в начало строки можно также с помощью f-строки:

el = '+' num = '91956612345' print(f'') 

Результат будет аналогичным первому способу:

Способ 3: преобразование в список

Если нужно вставить элемент в определенную позицию строки, в том числе – в начало, можно последовательно воспользоваться преобразованием строки в список и объединением списка в строку с помощью метода join():

el = '+' num = list('91956612345') (num).insert(0, el) print(''.join(num)) 

Способ 4: использование rjust

Метод rjust() используется для выравнивания строки по правому краю. В качестве параметров он принимает длину новой строки и символ, которым будут заполнены пустые позиции. По умолчанию в качестве заполнителя используется пробел, но ничто не мешает выбрать знак + :

num = "91956612345" print(num.rjust(12, '+')) 

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

Подведем итоги

Мы рассмотрели восемь простых и практичных способов добавления нужного элемента в начало списка и строки Python. Знаете какие-нибудь другие интересные способы вставки элементов? Поделитесь с нами в комментариях.

Материалы по теме

Источник

Prepend to a Python a List (Append at beginning)

Python List Prepend Cover Image

In this tutorial, you’ll learn how to use Python to prepend a list. While Python has a method to append values to the end of a list, there is no prepend method. By the end of this tutorial, you’ll have learned how to use the .insert() method and how to concatenate two lists to prepend.

You’ll also learn how to use the deque object to insert values at the front of a list. In many cases, this is the preferred method, as it’s significantly more memory efficient than other methods.

The Problem with Prepending a Python List

Python lists are a mutable container data type, meaning that they can be altered. Because of this, it can be tempting to add an item to a list. However, depending on the size of your list, this process can be immensely memory intensive.

The reason for this is that there is no “room” at the beginning of the list. When you add an item to the front of a list, Python needs to shift all other items forward. Later in this tutorial, you’ll learn about the deque data structure, which represents a double-ended queue. In these deque objects, items can be inserted freely at the beginning or end.

Using Insert to Prepend to a Python List

An intuitive way to add an item to the front of a Python list is to use the insert method. The .insert() method takes two parameters:

Let’s take a look at an example:

# Using .insert() to prepend to a Python list words = ['welcome', 'to', 'datagy'] words.insert(0, 'hello') print(words) # Returns: ['hello', 'welcome', 'to', 'datagy']

The operation takes place in-place, meaning that a new object doesn’t need to be created. In the following example, you’ll learn how to use the + operator to prepend an item to a list.

Using the + Operator to Prepend to a Python List

The Python + operator is an incredibly versatile operator. When combined with two lists, the two lists are added together, in the order in which they appear. This means that when we want to prepend an item (or multiple items), we can create a list containing this item.

We then only need to apply the + operator between the two lists to combine them. Let’s take a look at another example:

# Using + to prepend an item to a list words = ['welcome', 'to', 'datagy'] prefix = ['hello'] words = prefix + words print(words) # Returns: ['hello', 'welcome', 'to', 'datagy']

Similarly, we can use the augmented assignment operator to prepend an item to a list. The difference here is that we need to reassign to the prefix, not the other way around. This is demonstrated below:

# Using the augmented assignment operator to prepend an item to a list words = ['welcome', 'to', 'datagy'] prefix = ['hello'] prefix += words print(prefix) # Returns: ['hello', 'welcome', 'to', 'datagy']

In the next section, you’ll learn how to use list slicing to prepend to a Python list.

Using List Slicing to Prepend to a Python List

This method can feel a bit awkward, but it can also be a useful way to assign an item to the front of a list. We assign a list with a single value to the slice of [:0] of another list. This forces the item to be added before the 0th item.

Let’s take a look at an example:

# Using List Slicing to prepend to a Python List words = ['welcome', 'to', 'datagy'] words[:0] = ['hello'] print(words) # Returns: ['hello', 'welcome', 'to', 'datagy']

In the final section, you’ll learn the most memory-efficient way to add items to the front of a Python list.

Using Deque to Prepend to a Python List

Part of the incredibly versatile collections library is the deque class. This class represents a double-ended queue, which represent stacks or queues from other languages. The benefit of this is that the class allows you to prepend items to the left, without the memory implications of shifting all values.

Let’s take a look at an example:

# Using deque to prepend to a list in Python from collections import deque words = deque(['welcome', 'to', 'datagy']) words.appendleft('hello') print(words) # Returns: ['hello', 'welcome', 'to', 'datagy']

The benefit of this approach is noticeable when working with large lists. With smaller lists, you may not notice a benefit, but it’s a good idea to keep performance in mind.

Conclusion

In this tutorial, you learned how to prepend to a Python list. You first learned why prepending to a list can be a troublesome idea. Then, you learned how to use three different list methods, including .insert() , the + operator, and list indexing to prepend to a list. Finally, you learned how to use the collections deque object to prepend to a list in a memory-efficient manner.

Additional Resources

To learn more about related topics, check out the tutorials below:

Источник

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