Informatics 9. Билингвальный учебник - [12]
5. Use different methods.
Practice 2
1. Create two lists;
2. Add 5 elements to the first list using append() method;
3. Add 5 elements to the second list using extend() method;
4. The program should check the number you like exists in the list;
5. Check all items and print out elements that exist in both lists.
Hint: use for loop and in method.
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)
List.insert(pos2, first_element)
print(“List after swapping 1st and 3rd elements:”)
print(List)
Output
4
New List after pop: [1, 2, 3]
Keep in mind
list.pop(index)
Извлечение элемента из списка, функция без параметра удаляет по умолчанию последний элемент списка, в качестве параметра можно поставить произвольный индекс:
Если указанный индекс находится за пределами списка, выдаст ошибку IndexError.
Practice 3
1. Enter the number of elements in the list.
2. Enter the values of elements into the list.
3. Swap the first and last element in the list.
4. Print the newly formed list.
Terminology
swap – орынындарын алмастыру – менять
element – элемент – элемент
pop – шығарып алу – вывезти
even – жұп – четный
odd – тақ – нечетный
3.5 SORTING IN PYTHON LIST
You will:
Learn to swap elements in a list;
What’s the fastest way to alphabetize your bookshelf?
Функция сортировки списка sort ()
Вы можете использовать функцию сортировки для сортировки списка по возрастанию, убыванию или в особом порядке.
To sort the list in ascending order.
List.sort() - sorts the given list in ascending order.
This function can be used to sort a list of integers, floating point number, string, and others.
Example 1
List = [1, 3, 4, 2]
#Sorting list of Integers in ascending
List.sort()
print(List)
Output
[1, 2, 3, 4]
To sort the list in descending order.
List.sort(reverse = True) - sorts the given list in descending order.
Example 2
List = [1, 3, 4, 2]
# Sorting list of Integers in descending
List.sort(reverse = True)
print(List)
Output
[4, 3, 2, 1]
Practice 1
1. Create a new blank list
2. Add at least 7 fruits.
3. Sort your list in reverse alphabetic order.
4. Print List before and after sorting.
Practice 2
1. Create a new blank list named “bookshelf”.
2. Add names of your favorite books. At least 10 books.
3. Sort your books in alphabetic order.
4. Print your sorted bookshelf.
Python sorted()
The sorted() method sorts the elements of a given iterable in a specific order - Ascending or Descending.
The syntax of sorted() method is:
sorted(iterable[, key][, reverse])
sorted() method returns a sorted list from the given iterable.
Example 3
# vowels list
pyList = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’]
print(sorted(pyList))
# string
pyString = ‘Python’
print(sorted(pyString))
# vowels tuple
pyTuple = (‘e’, ‘a’, ‘u’, ‘o’, ‘i’)