Operations with lists in python

Списки (list). Функции и методы списков

Python 3 логотип

Сегодня я расскажу о таком типе данных, как списки, операциях над ними и методах, о генераторах списков и о применении списков.

Что такое списки?

Списки в Python — упорядоченные изменяемые коллекции объектов произвольных типов (почти как массив, но типы могут отличаться).

Чтобы использовать списки, их нужно создать. Создать список можно несколькими способами. Например, можно обработать любой итерируемый объект (например, строку) встроенной функцией list:

Список можно создать и при помощи литерала:

Как видно из примера, список может содержать любое количество любых объектов (в том числе и вложенные списки), или не содержать ничего.

И еще один способ создать список — это генераторы списков. Генератор списков — способ построить новый список, применяя выражение к каждому элементу последовательности. Генераторы списков очень похожи на цикл for.

Возможна и более сложная конструкция генератора списков:

Но в сложных случаях лучше пользоваться обычным циклом for для генерации списков.

Функции и методы списков

Создать создали, теперь нужно со списком что-то делать. Для списков доступны основные встроенные функции, а также методы списков.

Таблица «методы списков»

Метод Что делает
list.append(x) Добавляет элемент в конец списка
list.extend(L) Расширяет список list, добавляя в конец все элементы списка L
list.insert(i, x) Вставляет на i-ый элемент значение x
list.remove(x) Удаляет первый элемент в списке, имеющий значение x. ValueError, если такого элемента не существует
list.pop([i]) Удаляет i-ый элемент и возвращает его. Если индекс не указан, удаляется последний элемент
list.index(x, [start [, end]]) Возвращает положение первого элемента со значением x (при этом поиск ведется от start до end)
list.count(x) Возвращает количество элементов со значением x
list.sort(Operations with lists in python) Сортирует список на основе функции
list.reverse() Разворачивает список
list.copy() Поверхностная копия списка
list.clear() Очищает список

Нужно отметить, что методы списков, в отличие от строковых методов, изменяют сам список, а потому результат выполнения не нужно записывать в эту переменную.

   И, напоследок, примеры работы со списками:

Изредка, для увеличения производительности, списки заменяют гораздо менее гибкими массивами (хотя в таких случаях обычно используют сторонние библиотеки, например NumPy).

Для вставки кода на Python в комментарий заключайте его в теги

  • Книги о Python
  • GUI (графический интерфейс пользователя)
  • Курсы Python
  • Модули
  • Новости мира Python
  • NumPy
  • Обработка данных
  • Основы программирования
  • Примеры программ
  • Типы данных в Python
  • Видео
  • Python для Web
  • Работа для Python-программистов

Источник

List Operations in Python

List Operations in Python

The list is a data structuring method that allows storing the integers or the characters in an order indexed by starting from 0. List operations are the operations that can be performed on the data in the list data structure. A few of the basic list operations used in Python programming are extend(), insert(), append(), remove(), pop(), slice, reverse(), min() & max(), concatenate(), count(), multiply(), sort(), index(), clear(), etc.

Key Highlights

  • The Python List is one of the built-in data types of Python and the most flexible one. These are involved in the storage of the collection of data sets.
  • The elements of a list are in a defined order, and you can modify these elements. Either add, remove, or change the elements in the list.
  • It is easy to create the Python list; add some elements in square brackets, separating each element by comma and assigning it to a variable.
  • Python Lists allow you to perform various functions apart from simple operations like adding or deleting. You can remove any element irrespective of the position, reverse the order of the list, print the results in a specific sequence, and sort or even empty the elements in the list.

List Operations in Python

Some of the most widely used list operations in Python include the following:

1. append()

The append() method adds elements at the end of the list. This method can only add a single element at a time. You can use the append() method inside a loop to add multiple elements.

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] myList.append(4) myList.append(5) myList.append(6) for i in range(7, 9): myList.append(i) print(myList)

Append - Python List Operations

2. extend()

The extend() method adds more than one element at the end of the list. Although it can add more than one element, unlike append(), it adds them at the end of the list like append().

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] myList.extend([4, 5, 6]) for i in range(7, 11): myList.append(i) print(myList)

Extend - Python List Operations

3. insert()

The insert() method can add an element at a given position in the list. Thus, unlike append(), it can add elements at any position, but like append(), it can add only one element at a time. This method takes two arguments. The first argument specifies the position, and the second argument specifies the element to be inserted.

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] myList.insert(3, 4) myList.insert(4, 5) myList.insert(5, 6) print(myList)

Insert- Python List Operations

4. remove()

The remove() method removes an element from the list. Only the first occurrence of the same element is removed in the case of multiple occurrences.

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] myList.remove('makes learning fun!') print(myList)

Remove - Python List Operations

5. pop()

The method pop() can remove an element from any position in the list. The parameter supplied to this method is the element index to be removed.

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] myList.pop(3) print(myList)

pop method in python

6. slice

The slice operation is used to print a section of the list. The slice operation returns a specific range of elements. It does not modify the original list.

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] print(myList[:4]) # prints from beginning to end index print(myList[2:]) # prints from start index to end of list print(myList[2:4]) # prints from start index to end index print(myList[:]) # prints from beginning to end of list

Slice method

7. reverse()

You can use the reverse() operation to reverse the elements of a list. This method modifies the original list. We use the slice operation with negative indices to reverse a list without modifying the original. Specifying negative indices iterates the list from the rear end to the front end of the list.

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] print(myList[::-1]) # does not modify the original list myList.reverse() # modifies the original list print(myList)

Reverse method

8. len()

The len() method returns the length of the list, i.e., the number of elements in the list.

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] print(len(myList))

9. min() & max()

The min() method returns the minimum value in the list. The max() method returns the maximum value in the list. Both methods accept only homogeneous lists, i.e., lists with similar elements.

myList = [1, 2, 3, 4, 5, 6, 7] print(min(myList)) print(max(myList))

10. count()

The function count() returns the number of occurrences of a given element in the list.

myList = [1, 2, 3, 4, 3, 7, 3, 8, 3] print(myList.count(3))

11. concatenate

The concatenate operation merges two lists and returns a single list. The concatenation is performed using the + sign. It’s important to note that the individual lists are not modified, and a new combined list is returned.

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] yourList = [4, 5, 'Python', 'is fun!'] print(myList+yourList)

Concatenate method

12. multiply

Python also allows multiplying the list n times. The resultant list is the original list iterated n times.

myList = ['EduCBA', 'makes learning fun!'] print(myList*2)

Multiply method

13. index()

The index() method returns the position of the first occurrence of the given element. It takes two optional parameters – the beginning index and the end index. These parameters define the start and end position of the search area on the list. When you supply the begin and end indices, the element is searched only within the sub-list specified by those indices. When not supplied, the element is searched in the whole list.

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] print(myList.index('EduCBA')) # searches in the whole list print(myList.index('EduCBA', 0, 2)) # searches from 0th to 2nd position

Index method

14. sort()

The sort method sorts the list in ascending order. You can only perform this operation on homogeneous lists, which means lists with similar elements.

yourList = [4, 2, 6, 5, 0, 1] yourList.sort() print(yourList)

Sort method

15. clear()

This function erases all the elements from the list and empties them.

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!'] myList.clear()

Here the output is empty because it clears all the data.

16. copy()

The copy method returns the shallow copy list. Now the created list points to a different memory location than the original one. Hence any changes made to the list don’t affect another one.

even_numbers = [2, 4, 6, 8] value = even_numbers.copy() print('Copied List:', value)

Copy method

Conclusion

In Python, lists serve as a basic data structure that enables you to store and handle groups of values. They are ordered and changeable and can hold elements of any data type. Some commonly used operations on lists include creating a list, accessing features using indices, adding and removing elements, slicing a list, modifying elements, checking if an element exists, sorting a list, and reversing a list. These operations can be beneficial when working with large data sets or building complex algorithms in Python.

Frequently Asked Questions (FAQs)

Q1. Write down the syntax for the Python list.

Answer: You can easily create lists in Python by using square brackets. Add all the elements required in square brackets by assigning them to a variable. The list can store different kinds of data types.

Q2. What are the operations that can be performed with Python lists?

Answer: Certain familiar operations like adding and multiplying happen with Python lists. You can also perform operations such as slicing, indexing and checking for membership on lists.

Q3. What are the characteristics of list operations in Python?

Answer: These characteristics of list operations define their usage in performing certain operations.

  • The list is mutable, meaning the addition, removal, or substitution of elements is possible.
  • Whenever a new element is added to a list, it is added at the end, ensuring that the list maintains its ordered structure.
  • The list can have the same elements allowing duplicates.

We hope that this EDUCBA information on “List Operations in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Источник

Читайте также:  Php strpos массив значений
Оцените статью