Informatics 9. Билингвальный учебник | страница 24




Literacy

1. Explain the pros and cons of different ways of checking existence of element in the list.


Terminology

loop – цикл – цикл

element – элемент – элемент

initialize – инициализациялау – инициализировать

conventional – дəстүрлі – обычный


3.4 SWAPELEMENTSINLIST

You will:

Learn to swap elements in a list;


How many ways do you know to swap items from two boxes?

Обмен значениями двух переменных в Python

Обмен значениями двух переменных в Python на самом деле очень простая задача. Python позволяет довольно легко поменять два значения без большого объема кода. Проверьте, насколько легко поменять местами два числа, используя встроенные методы, приведенные ниже:


Example 1

x, y = 21, 64

print(x, y)

x, y = y, x

print(y, x)

Output

21 64 64 21


Python program to swap two elements in a list

Below given a program that swaps the two elements with given positions in the list.

Since the positions of the elements are known, we can simply swap the positions of the elements.


Example 2

List = [23, 65, 19, 90]

pos1, pos2 = 1, 3

print(“List before swapping: “, List)

List[pos1], List[pos2] = List[pos2], List[pos1]

print(“List after swapping 1st and 3rd

elements:”)

print(List)

Intput

List = [23, 65, 19, 90], pos1 = 1, pos2 = 3

Output

List before swapping: [23, 65, 19, 90]

List after swapping 1st and 3rd elements:

[23, 90, 19, 65]


Practice 1

1. Create new blank list

2. Add numbers from 1 to 10 using loop.

3. Swap elements with index 3 and 7.

4. Swap elements with index 3 and 5.

5. Print List before and after swapping.


Practice 2

1. Create new blank list

2. Add ODD numbers from 3 to 20 using loop.

3. Swap elements with index 2 and 6.

4. Print List before and after swapping.


list.pop()

pop() - извлечение элемента из списка, функция без параметра удаляет по умолчанию последний элемент списка.


Example 3

List = [ 1, 2, 3, 4]

print(List.pop())

print(“New List after pop: “, List)

Output

4

New List after pop: [1, 2, 3]


Example 4

List = [1, 2, 3, 4]

print(List.pop(2))

print(“New List after pop: “, List)

Output

3

New List after pop: [1, 2, 4]


Swap items in a list using Inbuilt list.pop() function

Pop the element at pos1 and store it in a variable. Similarly, pop the element at pos2 and store it in another variable. Now insert the two popped element at each other’s original position.


Example 5

List = [23, 65, 19, 90]

pos1, pos2 = 1, 3

print(“List before swapping: “, List)

first_element = List.pop(pos1)

second_element = List.pop(pos2 - 1)

List.insert(pos1, second_element)