Python add element to list first

Python add element to list 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) 

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

Читайте также:  Логические операции php больше

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

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. Знаете какие-нибудь другие интересные способы вставки элементов? Поделитесь с нами в комментариях.

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

Источник

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) 

Источник

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!

Источник

Append to Front of a List in Python

Append to Front of a List in Python

  1. Use insert() to Append an Element to the Front of a List in Python
  2. Use the + Operator to Append an Element to the Front of a List in Python
  3. Use Unpacking to Insert an Element Into the Beginning of a List

This tutorial will demonstrate different ways on how to append an element to the front of a list in Python.

Throughout the tutorial, a list of integers will be used as examples to focus on list insertion instead of inserting various data types since the list insertion approach should be the same regardless of what data type the list contains.

Use insert() to Append an Element to the Front of a List in Python

The insert() function inserts an element to the given index of an existing list. It accepts two parameters, the index to be inserted into and the value to insert.

For example, we’ll insert an element into an existing list of size 5 . To append an element to the front of the list using this function, we should set the first argument as 0 , which denotes that the insertion is done at index 0 — the beginning of the list.

int_list = [13, 56, 5, 78, 100]  int_list.insert(0, 24)  print(int_list) 

Use the + Operator to Append an Element to the Front of a List in Python

Another approach to append an element to the front of a list is to use the + operator. Using the + operator on two or more lists combines them in the specified order.

If you add list1 + list2 together, then it concatenates all the elements from list2 after the last element of list1 . For example, let’s add a single integer into the beginning of an already existing list using the + operator.

to_insert = 56 int_list = [13, 5, 78, 19, 66]  int_list = [to_insert] + int_list  print(int_list) 

Notice the to_insert variable is encapsulated with square brackets [] . This is done to convert the single integer into the list data type to make list addition possible.

Use Unpacking to Insert an Element Into the Beginning of a List

Unpacking is an operation in Python that allows unique iterable manipulations to be possible. Unpacking allows iterable assignment to be more flexible and efficient for the developers.

Unpacking also allows merging existing iterables, which is the operation that will be used to insert into the beginning of the list for this example.

To append an element to the beginning of a list using unpacking, we use the unpacking operator * to merge the single integer and the existing list, placing the integer at the beginning of the newly formed list.

to_insert = 7 int_list = [19, 22, 40, 1, 78]  int_list = [to_insert, *int_list]  print(int_list) 

Performance-wise, using unpacking is the fastest out of all the solutions mentioned. The insert() method is a close second to unpacking. Using the + operator is significantly slower than both the solutions mentioned above.

If you’re inserting into the beginning of a list with a significant number of elements, it’s best to use either unpacking or insert() for faster runtime.

Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.

Related Article — Python List

Источник

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