Список Python (з прикладами)

У цій статті ми дізнаємося все про списки Python, як вони створюються, нарізання списку, додавання або видалення елементів із них тощо.

Відео: Списки та кортежі Python

Python пропонує ряд складених типів даних, які часто називають послідовностями. Список є одним із найбільш часто використовуваних та дуже універсальних типів даних, що використовуються в Python.

Як створити список?

У програмуванні на Python список створюється шляхом розміщення всіх елементів (елементів) у квадратних дужках (), розділених комами.

Він може мати будь-яку кількість елементів, і вони можуть бути різного типу (ціле число, плаваюче число, рядок тощо).

 # empty list my_list = () # list of integers my_list = (1, 2, 3) # list with mixed data types my_list = (1, "Hello", 3.4)

Список може також мати інший список як елемент. Це називається вкладеним списком.

 # nested list my_list = ("mouse", (8, 4, 6), ('a'))

Як отримати доступ до елементів зі списку?

Існують різні способи отримання доступу до елементів списку.

Індекс списку

Ми можемо використовувати оператор індексу ()для доступу до елемента у списку. У Python індекси починаються з 0. Отже, список із 5 елементами матиме індекс від 0 до 4.

Спроба отримати доступ до індексів, відмінних від цих, призведе до IndexError. Індекс повинен бути цілим числом. Ми не можемо використовувати флоат або інші типи, це призведе до TypeError.

Доступ до вкладених списків здійснюється за допомогою вкладеного індексування.

 # List indexing my_list = ('p', 'r', 'o', 'b', 'e') # Output: p print(my_list(0)) # Output: o print(my_list(2)) # Output: e print(my_list(4)) # Nested List n_list = ("Happy", (2, 0, 1, 5)) # Nested indexing print(n_list(0)(1)) print(n_list(1)(3)) # Error! Only integer can be used for indexing print(my_list(4.0))

Вихідні дані

 poea 5 Traceback (останній дзвінок останній): Файл "", рядок 21, у TypeError: індекси списку повинні бути цілими чи фрагментами, а не плаваючими

Негативне індексування

Python дозволяє негативне індексування своїх послідовностей. Індекс -1 відноситься до останнього пункту, -2 до другого останнього пункту тощо.

 # Negative indexing in lists my_list = ('p','r','o','b','e') print(my_list(-1)) print(my_list(-5))

Коли ми запустимо вищезазначену програму, ми отримаємо такий результат:

 еп
Індексація списків у Python

Як нарізати списки в Python?

Ми можемо отримати доступ до ряду елементів у списку за допомогою оператора нарізки :(двокрапки).

 # List slicing in Python my_list = ('p','r','o','g','r','a','m','i','z') # elements 3rd to 5th print(my_list(2:5)) # elements beginning to 4th print(my_list(:-5)) # elements 6th to end print(my_list(5:)) # elements beginning to end print(my_list(:))

Вихідні дані

 ('o', 'g', 'r') ('p', 'r', 'o', 'g') ('a', 'm', 'i', 'z') ('p ',' r ',' o ',' g ',' r ',' a ',' m ',' i ',' z ')

Нарізання найкраще візуалізувати, враховуючи, що індекс знаходиться між елементами, як показано нижче. Отже, якщо ми хочемо отримати доступ до діапазону, нам потрібні два індекси, які виріжуть цю частину зі списку.

Нарізання елементів зі списку на Python

Як змінити або додати елементи до списку?

Списки можна змінювати, тобто їх елементи можна змінювати на відміну від рядка чи кортежу.

Ми можемо використовувати оператор присвоєння ( =) для зміни елемента або діапазону елементів.

 # Correcting mistake values in a list odd = (2, 4, 6, 8) # change the 1st item odd(0) = 1 print(odd) # change 2nd to 4th items odd(1:4) = (3, 5, 7) print(odd) 

Вихідні дані

 (1, 4, 6, 8) (1, 3, 5, 7)

Ми можемо додати один елемент до списку за допомогою append()методу або додати кілька елементів за допомогою extend()методу.

 # Appending and Extending lists in Python odd = (1, 3, 5) odd.append(7) print(odd) odd.extend((9, 11, 13)) print(odd)

Вихідні дані

 (1, 3, 5, 7) (1, 3, 5, 7, 9, 11, 13)

Ми також можемо використовувати +оператор для об'єднання двох списків. Це також називається конкатенацією.

*Оператор повторює список для заданого числа раз.

 # Concatenating and repeating lists odd = (1, 3, 5) print(odd + (9, 7, 5)) print(("re") * 3)

Вихідні дані

 (1, 3, 5, 9, 7, 5) ('re', 're', 're')

Крім того, ми можемо вставити один елемент у потрібне місце за допомогою методу insert()або вставити кілька елементів, стиснувши його в порожній фрагмент списку.

 # Demonstration of list insert() method odd = (1, 9) odd.insert(1,3) print(odd) odd(2:2) = (5, 7) print(odd)

Вихідні дані

 (1, 3, 9) (1, 3, 5, 7, 9)

Як видалити або видалити елементи зі списку?

Ми можемо видалити один або кілька елементів зі списку за допомогою ключового слова del. Він навіть може повністю видалити список.

 # Deleting list items my_list = ('p', 'r', 'o', 'b', 'l', 'e', 'm') # delete one item del my_list(2) print(my_list) # delete multiple items del my_list(1:5) print(my_list) # delete entire list del my_list # Error: List not defined print(my_list)

Вихідні дані

 ('p', 'r', 'b', 'l', 'e', ​​'m') ('p', 'm') Traceback (останній дзвінок останній): Файл "", рядок 18, у NameError: ім'я 'my_list' не визначено

Ми можемо використовувати remove()метод для видалення даного елемента або pop()метод для видалення елемента за даним індексом.

The pop() method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure).

We can also use the clear() method to empty a list.

 my_list = ('p','r','o','b','l','e','m') my_list.remove('p') # Output: ('r', 'o', 'b', 'l', 'e', 'm') print(my_list) # Output: 'o' print(my_list.pop(1)) # Output: ('r', 'b', 'l', 'e', 'm') print(my_list) # Output: 'm' print(my_list.pop()) # Output: ('r', 'b', 'l', 'e') print(my_list) my_list.clear() # Output: () print(my_list)

Output

 ('r', 'o', 'b', 'l', 'e', 'm') o ('r', 'b', 'l', 'e', 'm') m ('r', 'b', 'l', 'e') ()

Finally, we can also delete items in a list by assigning an empty list to a slice of elements.

 >>> my_list = ('p','r','o','b','l','e','m') >>> my_list(2:3) = () >>> my_list ('p', 'r', 'b', 'l', 'e', 'm') >>> my_list(2:5) = () >>> my_list ('p', 'r', 'm')

Python List Methods

Methods that are available with list objects in Python programming are tabulated below.

They are accessed as list.method(). Some of the methods have already been used above.

Python List Methods
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of the number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list

Some examples of Python list methods:

 # Python list methods my_list = (3, 8, 1, 6, 0, 8, 4) # Output: 1 print(my_list.index(8)) # Output: 2 print(my_list.count(8)) my_list.sort() # Output: (0, 1, 3, 4, 6, 8, 8) print(my_list) my_list.reverse() # Output: (8, 8, 6, 4, 3, 1, 0) print(my_list)

Output

 1 2 (0, 1, 3, 4, 6, 8, 8) (8, 8, 6, 4, 3, 1, 0)

List Comprehension: Elegant way to create new List

List comprehension is an elegant and concise way to create a new list from an existing list in Python.

A list comprehension consists of an expression followed by for statement inside square brackets.

Here is an example to make a list with each item being increasing power of 2.

 pow2 = (2 ** x for x in range(10)) print(pow2)

Output

 (1, 2, 4, 8, 16, 32, 64, 128, 256, 512)

This code is equivalent to:

 pow2 = () for x in range(10): pow2.append(2 ** x)

A list comprehension can optionally contain more for or if statements. An optional if statement can filter out items for the new list. Here are some examples.

 >>> pow2 = (2 ** x for x in range(10) if x> 5) >>> pow2 (64, 128, 256, 512) >>> odd = (x for x in range(20) if x % 2 == 1) >>> odd (1, 3, 5, 7, 9, 11, 13, 15, 17, 19) >>> (x+y for x in ('Python ','C ') for y in ('Language','Programming')) ('Python Language', 'Python Programming', 'C Language', 'C Programming')

Other List Operations in Python

List Membership Test

We can test if an item exists in a list or not, using the keyword in.

 my_list = ('p', 'r', 'o', 'b', 'l', 'e', 'm') # Output: True print('p' in my_list) # Output: False print('a' in my_list) # Output: True print('c' not in my_list)

Output

 True False True

Iterating Through a List

Using a for loop we can iterate through each item in a list.

 for fruit in ('apple','banana','mango'): print("I like",fruit)

Output

 Мені подобається яблуко Мені подобається банан Мені подобається манго

Цікаві статті...