Как сделать копию списка python
Перейти к содержимому

Как сделать копию списка python

  • автор:

copy — Shallow and deep copy operations¶

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

Return a shallow copy of x.

Return a deep copy of x.

exception copy. Error ¶

Raised for module specific errors.

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Two problems often exist with deep copy operations that don’t exist with shallow copy operations:

Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.

Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.

The deepcopy() function avoids these problems by:

keeping a memo dictionary of objects already copied during the current copying pass; and

letting user-defined classes override the copying operation or the set of components copied.

This module does not copy types like module, method, stack trace, stack frame, file, socket, window, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module.

Shallow copies of dictionaries can be made using dict.copy() , and of lists by assigning a slice of the entire list, for example, copied_list = original_list[:] .

Classes can use the same interfaces to control copying that they use to control pickling. See the description of module pickle for information on these methods. In fact, the copy module uses the registered pickle functions from the copyreg module.

In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__() . The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument. The memo dictionary should be treated as an opaque object.

Discussion of the special methods used to support object state retrieval and restoration.

Six ways to Copy List items in Python

I like to learn cool stuff about python, I have started my Python journey one year ago. Now I am going through the basics of the python to learn more.

I have come across Six ways to copy list items from one list to another in python.

Let's have look at it.

Suppose we want to copy the content of old_list to new_list,

1.Using the Copy() Method: the Copy method of the list object is used to copy only the content inside the list. So the new list will not have the same reference id or memory location. so if we make any changes in the new_list it will not get reflected in the old_ist.

2. Using list() function: List() is built-in function in python. it is also used to create a new list in python. If we pass old_list as an argument inside this function. It copies the content of the old_list and generates a new_list.

The new list will not have same reference id because only content gets copied in this case

Note: Here I have intentionally used copy() as Method and list() as a function to point out the difference. Methods are always called on an object using ‘.’ operator, while function may not. All method is Function but the reverse may not be true.

3. Using List Slicing: List slicing is a way to extract data from a list. So using list slicing if we extract all the content from one list, the new list will have all the content from the old list.

Again this method will only copy content not reference id.

4. Shallow Copy: We can use the copy function of the copy module to get content from one list to another. Again it only copies the content, so the new list will have new Reference id.

5. Deep Copy: We can also use the Deep Copy function of the copy module in the same way as Shallow Copy. Both function works the same for a Normal List having simple content like shown in the example.

There is a difference in the behavior of both the function of the copy module in the case of the Nested List(List inside List).

If you want to know more about the difference between Shallow Copy and Deep Copy feel free to check this link

Suppose we want to copy the content as well as the reference of old_list to new_list,

6. Direct Assigning: If we Assign old_list to the new_list it copies content as well as Reference so changes will be reflected in old_list if it is done in the new_list.

Списки в Python

Всем привет! В этой статье мы позна­комимся с методами для работы со спис­ками в python . Но сначала вспомним, что такое список? Список — это изме­няемый и последовательный тип данных. Это значит, что мы можем добавлять, удалять и изменять любые элементы списка.

Начнем с метода append() , который добавляет элемент в конец списка:

# Создаем список, состоящий из четных чисел от 0 до 8 включительно
numbers = list ( range ( 0 , 10 , 2 ))
# Добавляем число 200 в конец списка
numbers. append ( 200 )
print (numbers)
# [0, 2, 4, 6, 8, 200]
numbers. append ( 1 )
numbers. append ( 2 )
numbers. append ( 3 )
print (numbers)
# [0, 2, 4, 6, 8, 200, 1, 2, 3]

Мы можем передавать методу append() абсолютно любые значения:

all_types = [ 10 , 3.14 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]]
all_types. append ( 1024 )
all_types. append ( ‘Hello world!’ )
all_types. append ([ 1 , 2 , 3 ])
print (all_types)
# [10, 3.14, ‘Python’, [‘I’, ‘am’, ‘list’], 1024, ‘Hello world!’, [1, 2, 3]]

Метод append() отлично выпол­няет свою функцию. Но, что делать, если нам нужно добавить элемент в сере­дину списка? Это умеет метод insert () . Он добавляет элемент в список на произ­вольную позицию. insert() принимает в качестве первого аргу­мента позицию, на которую нужно вставить элемент, а вторым — сам элемент.

# Создадим список чисел от 0 до 9
numbers = list ( range ( 10 ))
# Добавление элемента 999 на позицию с индексом 0
numbers. insert ( 0 , 999 )
print (numbers)
# [999, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers. insert ( 2 , 1024 )
print (numbers)
# [999, 0, 1024, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers. insert ( 5 , ‘Засланная строка-шпион’ )
print (numbers)
# [999, 0, 1024, 1, 2, ‘Засланная строка-шпион’, 3, 4, 5, 6, 7, 8, 9]

Отлично! Добавлять элементы в список мы научи­лись, осталось понять, как их из него удалять. Метод pop() удаляет эле­мент из списка по его индексу:

numbers = list ( range ( 10 ))
print (numbers)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Удаляем первый элемент
numbers. pop ( 0 )
print (numbers)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers. pop ( 0 )
print (numbers)
# [2, 3, 4, 5, 6, 7, 8, 9]
numbers. pop ( 2 )
print (numbers)
# [2, 3, 5, 6, 7, 8, 9]
# Чтобы удалить последний элемент, вызовем метод pop без аргументов
numbers. pop ()
print (numbers)
# [2, 3, 5, 6, 7, 8]
numbers. pop ()
print (numbers)
# [2, 3, 5, 6, 7]

Теперь мы знаем, как удалять элемент из списка по его инде­ксу. Но что, если мы не знаем индекса элемента, но знаем его значение? Для такого случая у нас есть метод remove() , кото­рый удаляет пер­вый найденный по значению элемент в списке.

all_types = [ 10 , ‘Python’ , 10 , 3.14 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]]
all_types. remove ( 3.14 )
print (all_types)
# [10, ‘Python’, 10, ‘Python’, [‘I’, ‘am’, ‘list’]]
all_types. remove ( 10 )
print (all_types)
# [‘Python’, 10, ‘Python’, [‘I’, ‘am’, ‘list’]]
all_types. remove ( ‘Python’ )
print (all_types) # [10, ‘Python’, [‘I’, ‘am’, ‘list’]]

А сейчас немного посчитаем, посчитаем эле­менты списка с помощью метода count()

numbers = [ 100 , 100 , 100 , 200 , 200 , 500 , 500 , 500 , 500 , 500 , 999 ]
print (numbers. count ( 100 ))
# 3
print (numbers. count ( 200 ))
# 2
print (numbers. count ( 500 ))
# 5
print (numbers. count ( 999 ))
# 1

В программировании, как и в жизни, проще работать с упоря­доченными дан­ными, в них легче ори­енти­ро­ваться и что-либо искать. Метод sort() сорти­рует список по воз­раста­нию значений его элементов.

numbers = [ 100 , 2 , 11 , 9 , 3 , 1024 , 567 , 78 ]
numbers. sort ()
print (numbers)
# [2, 3, 9, 11, 78, 100, 567, 1024]
fruits = [ ‘Orange’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. sort ()
print (fruits)
# [‘Apple’, ‘Banan’, ‘Grape’, ‘Orange’, ‘Peach’]

Мы можем изменять порядок сортировки с помощью пара­метра reverse . По умол­чанию этот параметр равен False

fruits = [ ‘Orange’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. sort ()
print (fruits)
# [‘Apple’, ‘Banan’, ‘Grape’, ‘Orange’, ‘Peach’]
fruits. sort ( reverse = True )
print (fruits)
# [‘Peach’, ‘Orange’, ‘Grape’, ‘Banan’, ‘Apple’]

Иногда нам нужно перевернуть список, не спраши­вайте меня зачем. Для этого в самом лучшем языке прог­рам­миро­вания на этой планете JavaScr..­Python есть метод reverse() :

numbers = [ 100 , 2 , 11 , 9 , 3 , 1024 , 567 , 78 ]
numbers. reverse ()
print (numbers)
# [78, 567, 1024, 3, 9, 11, 2, 100]
fruits = [ ‘Orange ‘, ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. reverse ()
print (fruits)
# [‘Apple’, ‘Banan’, ‘Peach’, ‘Grape’, ‘Orange’]

Допустим, у нас есть два списка и нам нужно их объединить. Програм­мисты на C++ cразу же кинулись писать циклы for , но мы пишем на python , а в python у спис­ков есть полез­ный метод extend() . Этот метод вызы­вается для одного списка, а в качестве аргу­мента ему пере­дается другой список, extend() запи­сывает в конец первого из них начало вто­рого:

fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
vegetables = [ ‘Tomato’ , ‘Cucumber’ , ‘Potato’ , ‘Carrot’ ]
fruits. extend (vegetables)
print (fruits)
# [‘Banana’, ‘Apple’, ‘Grape’, ‘Tomato’, ‘Cucumber’, ‘Potato’, ‘Carrot’]

В природе существует специ­аль­ный метод для очистки списка — clear()

fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
vegetables = [ ‘Tomato’ , ‘Cucumber’ , ‘Potato’ , ‘Carrot’ ]
fruits. clear ()
vegetables. clear ()
print (fruits)
# []
print (vegetables)
# []

Осталось совсем чуть-чуть всего лишь пара мето­дов, так что делаем последний рывок! Метод index() возв­ращает индекс эле­мента. Рабо­тает это так: вы пере­даете в качестве аргу­мента в index() значение элемента, а метод возв­ращает его индекс:

fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
print (fruits. index ( ‘Apple’ ))
# 1
print (fruits. index ( ‘Banana’ ))
# 0
print (fruits. index ( ‘Grape’ ))
# 2

Финишная прямая! Метод copy() , только не падайте, копирует список и возвра­щает его брата-близнеца. Вообще, копи­ро­вание списков — это тема доста­точно инте­ресная, давай­те рас­смотрим её по-подробнее.

Во-первых, если мы просто прис­воим уже сущест­вующий список новой пере­менной, то на первый взгляд всё выглядит неплохо:

fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits
print (fruits)
# [‘Banana’, ‘Apple’, ‘Grape’]
print (new_fruits)
# [‘Banana’, ‘Apple’, ‘Grape’]

Но есть одно маленькое «НО»:

fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits
fruits. pop ()
print (fruits)
# [‘Banana’, ‘Apple’]
print (new_fruits)
# Внезапно, из списка new_fruits исчез последний элемент
# [‘Banana’, ‘Apple’]

При прямом присваивании спис­ков копи­рования не проис­ходит. Обе пере­менные начи­нают ссылаться на один и тот же список! То есть если мы изме­ним один из них, то изме­нится и другой. Что же тогда делать? Пользоваться методом copy() , конечно:

fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits. copy ()
fruits. pop ()
print (fruits)
# [‘Banana’, ‘Apple’]
print (new_fruits)
# [‘Banana’, ‘Apple’, ‘Grape’]

Отлично! Но что если у нас список в списке? Скопируется ли внутренний список с помощью метода copy() — нет:

fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ , [ ‘Orange’ , ‘Peach’ ]]
new_fruits = fruits. copy ()
fruits[ — 1 ]. pop ()
print (fruits)
# [‘Banana’, ‘Apple’, ‘Grape’, [‘Orange’]]
print (new_fruits)
# [‘Banana’, ‘Apple’, ‘Grape’, [‘Orange’]]

Скопируйте или клонируйте список Python

В этом посте мы обсудим, как скопировать или клонировать список в Python.

Присваивания не копируют списки Python, поскольку они просто создают привязки между исходным и скопированным списками. Это означает, что изменения, сделанные в исходном списке, будут видны в скопированном списке. В этой статье рассматриваются различные способы выполнения общей операции неглубокого копирования в Python.

1. Использование copy() функция

Стандартное решение для возврата неглубокой копии списка — встроенный copy() функция. Эта функция доступна для списков, наборов и словарей.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *