Python list поменять элементы местами

Методы списка

В Python у списков имеется одиннадцать методов. Условно разделим их на группы:

  • увеличивающие количество элементов — append , extend , insert
  • уменьшающие количество элементов — clear , pop , remove
  • изменяющие порядок элементов — reverse , sort
  • методы «поиска» — index , count
  • копирование списка — copy

Методы append и extend производят добавление в конец списка. Разница между ними заключается в том, что с помощью append можно добавить только один элемент, в то время extend позволяет расширить список сразу на несколько. При этом оба метода принимают один аргумент. В случае extend это должна быть итерируемая последовательность (кортеж, список, строка и другое), каждый элемент которой станет отдельным элементом списка.

>>> lst = ['a', 45, 89, 'who'] >>> lst.append(67) >>> lst ['a', 45, 89, 'who', 67]
>>> b [1, 2, 3] >>> c = (9, 10) >>> b.extend(c) >>> b [1, 2, 3, 9, 10] >>> b.extend("abc") >>> b [1, 2, 3, 9, 10, 'a', 'b', 'c'] >>> b.extend([12, 19]) >>> b [1, 2, 3, 9, 10, 'a', 'b', 'c', 12, 19]

Если требуется вставить элемент в произвольное место списка, используется метод insert . Он принимает два аргумента: сначала индекс, потом значение. Вставка элемента происходит перед элементом, который до этого занимал указанную позицию.

>>> lst.insert(0,10) >>> lst [10, 'a', 45, 89, 'who', 67, 'a1', (1, 2, 3)] >>> lst.insert(len(lst),10) >>> lst [10, 'a', 45, 89, 'who', 67, 'a1', (1, 2, 3), 10] >>> lst.insert(3, 10) >>> lst [10, 'a', 45, 10, 89, 'who', 67, 'a1', (1, 2, 3), 10]

Для удаления из списка одного элемента используют методы remove и pop . Метод remove принимает значение удаляемого элемента, и удаляет первое его вхождение. Если элемента нет в списке, возникает исключение ValueError . Метод pop удаляет элемент по индексу. При этом возвращает удаленное из списка значение в программу. Вызов pop() без аргументов удаляет и возвращает последний элемент. Метод pop генерирует исключение IndexError , если указан индекс за пределами диапазона индексов списка.

lst = [4, 3, 5, 1, 8, 1] d = int(input()) try: lst.remove(d) except ValueError: print('No the item') print(lst)
2 No the item [4, 3, 5, 1, 8, 1]
lst = ['a', 'f', 'b', 'x', 'y', 'k'] i = int(input()) try: value = lst.pop(i) except IndexError: value = 'Index Error' print(value)

Метод clear удаляет все элементы из списка.

Читайте также:  Sololearn задачи программирования python

Метод reverse изменяет порядок элементов на обратный. Метод переворачивает список на месте, то есть тот, к которому применяется.

>>> lst ['a', 10, 89, 'who', 67, 'a1', (1, 2, 3), 10] >>> lst.reverse() >>> lst [10, (1, 2, 3), 'a1', 67, 'who', 89, 10, 'a']

Метод sort выполняет сортировку списка на месте (список изменяется, а не возвращается новый). Если sort() вызывается без аргументов, сортировка происходит по возрастанию. Для сортировки по убыванию следует именованному параметру reverse присвоить True .

>>> li = [4, 1, 9, 5] >>> li.sort() >>> li [1, 4, 5, 9]
>>> st = [4, 2, 7, 5] >>> st.sort(reverse=True) >>> st [7, 5, 4, 2]

Для более сложных сортировок используется параметр key , которому присваивается функция, выполняющая действия над каждым элементом списка. Сортировка происходит на основе вернувшихся значений. Подробнее об этом в этой статье.

>>> n = [-4, 3, 9, -5, 2] >>> n.sort(key=lambda i: abs(i)) >>> n [2, 3, -4, -5, 9]

Метод count считает, сколько раз в списке встречается переданный аргумент.

Метод index возвращает индекс указанного элемента. Если таких значений несколько, метод вернет индекс только первого. Если таких элементов нет, генерируется исключение. Вторым и третьим аргументом можно указать срез для поиска.

>>> a = ['a', 'c', 'e', 'a', 'b'] >>> a.index('a') 0 >>> a.index('a', 2) 3 >>> a.index('a', 2, 4) 3 >>> a.index('a', 2, 3) Traceback (most recent call last): File "", line 1, in ValueError: 'a' is not in list

Метод copy создает поверхностную копию списка. Так при наличии вложенных списков копируются не они сами, а ссылки на них. В результате изменение вложенных списков через список-оригинал будет видно также в списке-копии.

>>> a = [1, 2] >>> b = a.copy() >>> b.append(3) >>> a [1, 2] >>> b [1, 2, 3]
>>> c = [1, 2, [3, 4]] >>> d = c.copy() >>> d.append(5) >>> c[2].append(6) >>> c [1, 2, [3, 4, 6]] >>> d [1, 2, [3, 4, 6], 5]

Источник

Читайте также:  JavaScript Radio Button

Swap Elements of a List in Python

Swap Elements of a List in Python

  1. Use the Assignment Operator to Swap Elements of a List in Python
  2. Use the Third Variable to Swap Elements of a List in Python
  3. Use the pop() Function to Swap Elements of a List in Python

A list is a mutable (changeable) data structure in Python that stores an ordered collection of items. In this article, we will look at a few different ways to swap the elements of a list.

Use the Assignment Operator to Swap Elements of a List in Python

One of the easiest and most commonly used methods to swap a list of elements is through the assignment operator and comma.

In the following code, we have created a list and exchanged the values of index 1 with index 3 using the assignment operator that will assign the corresponding values from the right side of the assignment operator to the left variables.

#Python 3.x list = [6, 2, 7, 8] print('list before swapping:', list) list[1], list[3] = list[3], list[1] print('list after swapping:', list) 
#Python 3.x list before swapping: [6, 2, 7, 8] list after swapping: [6, 8, 7, 2] 

Using the assignment operator, we can swap the values of only two variables at a time. If we want to exchange multiple values, we can do it using a loop.

In the following code, the variables i and j will hold the index of the elements to swap. The values of indexes 0 and 3 will exchange in the first iteration, and the elements of indexes 4 and 6 will switch in the second iteration.

#Python 3.x list = [6, 2, 7, 8, 5, 9, 10, 3, ] print('list before swapping:', list) for i,j in [(0,3),(4,6)]:  list[i], list[j] = list[j], list[i] print('list after swapping:', list) 
#Python 3.x list before swapping: [6, 2, 7, 8, 5, 9, 10, 3] list after swapping: [8, 2, 7, 6, 10, 9, 5, 3] 

Use the Third Variable to Swap Elements of a List in Python

We always need a third variable if we do not swap elements directly using the first approach. The third variable will temporarily hold the value of an index because we will lose it in the actual index after swapping.

Читайте также:  Приведение ссылочных типов java

In the following code, we have assigned the value of index 1 to the temp variable and index 3 to index 1 . Then we have assigned the value of temp (stored value of index 1 ) to index 3 .

#Python 3.x list = [6, 2, 7, 8] print('list before swapping:', list) temp = list[1] list[1] = list[3] list[3] = temp print('list after swapping:', list) 
#Python 3.x list before swapping: [6, 2, 7, 8] list after swapping: [6, 8, 7, 2] 

Use the pop() Function to Swap Elements of a List in Python

The pop() function with a list removes and returns the value from a specified index. In the following code, we have popped two elements from the list using their index and stored the returned values into two variables.

An important thing here is that we have used index 1 to remove the value 2 , but we have used index 2 to clear the value 8 . Because after we pop an item from the list, it will have a total of three elements.

So the index of 8 will be 2 . Finally, we have inserted these values again in the list by specifying the indexes in reverse order.

#Python 3.x list = [6, 2, 7, 8] print('list before swapping:', list) val1 = list.pop(1) val2 = list.pop(2) list.insert(1, val2) list.insert(2, val1) print('list after swapping:', list) 
#Python 3.x list before swapping: [6, 2, 7, 8] list after swapping: [6, 8, 7, 2] 

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

Related Article — Python List

Источник

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