Как скопировать list в list c
Перейти к содержимому

Как скопировать list в list c

  • автор:

Python List copy()

The copy() method returns a shallow copy of the list.

Example

# mixed list prime_numbers = [2, 3, 5] 
# copying a list numbers = prime_numbers.copy()
print('Copied List:', numbers) # Output: Copied List: [2, 3, 5]

copy() Syntax

The syntax of the copy() method is:

new_list = list.copy()

copy() Parameters

The copy() method doesn’t take any parameters.

copy() Return Value

The copy() method returns a new list. It doesn’t modify the original list.

Example: Copying a List

# mixed list my_list = ['cat', 0, 6.7] 
# copying a list new_list = my_list.copy()
print('Copied List:', new_list)

Output

Copied List: ['cat', 0, 6.7]

If you modify the new_list in the above example, my_list will not be modified.

List copy using =

We can also use the = operator to copy a list. For example,

old_list = [1, 2, 3] new_list = old_list

Howerver, there is one problem with copying lists in this way. If you modify new_list , old_list is also modified. It is because the new list is referencing or pointing to the same old_list object.

old_list = [1, 2, 3] 
# copy list using = new_list = old_list
# add an element to list new_list.append('a') print('New List:', new_list) print('Old List:', old_list)

Output

Old List: [1, 2, 3, 'a'] New List: [1, 2, 3, 'a']

However, if you need the original list unchanged when the new list is modified, you can use the copy() method.

Example: Copy List Using Slicing Syntax

# shallow copy using the slicing syntax # mixed list list = ['cat', 0, 6.7] 
# copying a list using slicing new_list = list[:]
# Adding an element to the new list new_list.append('dog') # Printing new and old list print('Old List:', list) print('New List:', new_list)

Output

Old List: ['cat', 0, 6.7] New List: ['cat', 0, 6.7, 'dog']

How to copy or clone a C# list?

Now declare a string array and use the CopyTo() method to copy.

string[] arr = new string[20]; list1.CopyTo(arr);

Let us see the complete code to copy a list into a one-dimensional array.

Example

using System; using System.Collections.Generic; using System.Linq; public class Demo < public static void Main() < List < string >list1 = new List < string >(); list1.Add("One"); list1.Add("Two"); list1.Add("Three"); list1.Add("Four"); Console.WriteLine("First list. "); foreach(string value in list1) < Console.WriteLine(value); >string[] arr = new string[20]; list1.CopyTo(arr); Console.WriteLine("After copy. "); foreach(string value in arr) < Console.WriteLine(value); >> >

Samual Sam

Learning faster. Every day.

How to Copy a List in Python (5 Techniques w/ Examples)

Lists are commonly used data structures in Python. We will often encounter situations wherein we need to make a copy of a list, and you may ask yourself, «How can I copy a list in Python?» or «Which copy method suits my requirements best?»

This tutorial will teach you how to copy or clone a list using several different techniques:

  • The assignment operator
  • The slicing syntax
  • The list.copy() method
  • The copy.copy() function
  • The copy.deepcopy() function

We will also discuss their usage and technical aspects in detail.

Copy a List Using the Assignment Operator

Suppose you use the assignment operator (=) to copy a list by assigning an existing list variable to a new list variable. In this case, you’re not actually creating a copy of the list; you’re just creating an alias that points to the exact same location in memory where the original list object exists. Let’s expand on the details and look closer.

Suppose we have the list variable, org_list , defined as follows:

org_list = [1, 2, ['a', 'b', 'c'], 3]

Then, we assign it to a new variable, cpy_list , hoping to make a copy of it for future use:

cpy_list = org_list

However, you need to know the variable cpy_list isn’t a true copy of the original list. You may ask, «Why isn’t it a true copy of the original list?» This is a great question because, as you’ll see below, printing these two variables returns the exact the same values.

print('Original List:', org_list) print('Copied List:', cpy_list)
Original List: [1, 2, ['a', 'b', 'c'], 3] Copied List: [1, 2, ['a', 'b', 'c'], 3]

As expected, the lists contain the same values. But, let’s see what happens if we modify the original list.

org_list.append('Dataquest') print('Original List:', org_list) print('Copied List:', cpy_list)
Original List: [1, 2, ['a', 'b', 'c'], 3, 'Dataquest'] Copied List: [1, 2, ['a', 'b', 'c'], 3, 'Dataquest']

Any modification to the original list will change the copied list, too.

The following illustration shows what’s happening once the source code is executed.

In fact, when you assign one variable to another, both variables are referencing the same object in memory, not two separate ones. This means both variables point to the same object via their references. When more than one variable references the same object, it’s called a shared reference or object.

Any modification to a shared mutable object via one of the variables that points to it affects the other variable that references the same object.

So, using the assignment operator doesn’t make a true copy of a list; it just creates an alias for the same object in memory.

But what if we want to make an independent copy of a list? In the following section, we’ll learn how to make shallow copies of a list.

The Shallow Copy Techniques

We just learned that assignments always store references to objects and don’t make an actual copy of those objects. However, it’s essential to know that changing a mutable object affects other objects that use the same reference in our code. So, we need to let Python know explicitly to copy an object if we want more than just a copy of the reference to that object. Generally speaking, there are two ways of making an independent copy of a list: a shallow copy and a deep copy. This section will discuss shallow copy and the different ways of implementing it.

Simply put, making a shallow copy of a compound list creates a new compound list and uses the references to the objects that the original list used.

NOTE: A compound object is an object that contains other objects, e.g., lists or dictionaries.

Shallow Copy Using List Slicing

To understand the shallow copy concept, let’s begin with an example. Assume we have a compound list as follows:

org_list = [1, 2, ['a', 'b', 'c'], 3]

Then, we can create a shallow copy of it using list slicing syntax:

cpy_list = org_list[:]

If we run the following print statements, we can see, both return exactly the same values.

print('Original List:', org_list) print('Copied List:', cpy_list)
Original List: [1, 2, ['a', 'b', 'c'], 3] Copied List: [1, 2, ['a', 'b', 'c'], 3]

Now, let’s append a new item to the original list and run the print statements again:

org_list.append('Dataquest') print('Original List:', org_list) print('Copied List:', cpy_list)
Original List: [1, 2, ['a', 'b', 'c'], 3, 'Dataquest'] Copied List: [1, 2, ['a', 'b', 'c'], 3]

The modification doesn’t affect the copied list. But, this isn’t the whole story. Let’s try another scenario and change one of the items in the nested list to see what happens:

org_list[2][0] = 'X' print('Original List:', org_list) print('Copied List:', cpy_list)
Original List: [1, 2, ['X', 'b', 'c'], 3, 'Dataquest'] Copied List: [1, 2, ['X', 'b', 'c'], 3]

Although making a shallow copy of a list produces a true copy of the original list, any modifications to the nested elements within it will be reflected in both lists. The reason is that the nested list in the copied list uses the same shared reference as the one in the original list. In other words, the nested lists in the copied list are tied to the nested lists in the original list. This is why we call it a shallow copy — because only a new top-level object is created while anything deeper uses a shared reference with the original list.

Now, let’s look at some other ways of making shallow copies of a list.

The Python list.copy() Method

Earlier, we discussed creating a shallow copy via the slicing syntax. In this section, we’ll learn about a built-in method that Python programmers commonly use for copying lists. The Python copy() method returns a shallow copy of the list without taking any parameters. Let’s try it out:

org_list = [1, 2, ['a', 'b', 'c'], 3] cpy_list = org_list.copy() print('Original List: ', org_list, ' @', id(org_list)) print('Copied List: ', cpy_list, ' @', id(cpy_list))
Original List: [1, 2, ['a', 'b', 'c'], 3] @ 140532024657920 Copied List: [1, 2, ['a', 'b', 'c'], 3] @ 140532024657600

Although org_list and cpy_list have the same values, as the output from the id() function shows, they end up in different locations in memory. However, exposing the memory addresses of the inner lists in both the original and copied lists reveals that they refer to the same location in memory, meaning we made a shallow copy of the original list.

org_list[2][0] = 'X' print('Inner List in Original: ', org_list[2],' @', id(org_list[2])) print('Inner List in Shallow Copied: ', cpy_list[2], ' @', id(cpy_list[2]))
Inner List in Original: ['X', 'b', 'c'] @ 140532024655936 Inner List in Shallow Copied: ['X', 'b', 'c'] @ 140532024655936

The Python copy.copy() Function

The other useful way of making a shallow copy of a list is the copy.copy() function. To use it, we import the copy module and then pass the list we want to copy to the copy.copy() function. Let’s try it out:

import copy org_list = [1, 2, ['a' ,'b' ,'c'], 3] cpy_list = copy.copy(org_list) print('Original List: ', org_list, ' @', id(org_list)) print('Copied List: ', cpy_list, ' @', id(cpy_list))
Original List: [1, 2, ['a', 'b', 'c'], 3] @ 140532024760320 Copied List: [1, 2, ['a', 'b', 'c'], 3] @ 140532024402048

Now, let’s append a new item to the original list, print both lists again, and check the output; nevertheless, we can predict the output before running the code below.

org_list.append('Dataquest') print('Original List: ', org_list, ' @', id(org_list)) print('Copied List: ', cpy_list, ' @', id(cpy_list))
Original List: [1, 2, ['a', 'b', 'c'], 3, 'Dataquest'] @ 140532024760320 Copied List: [1, 2, ['a', 'b', 'c'], 3] @ 140532024402048

The copy.copy() method has made a true copy of the original list. However, it’s still a shallow copy, and the nested lists refer to exactly the same memory location. In other words, the copy.copy() function only makes top-level copies and doesn’t copy nested objects. So, any modifications in either the original or copied list’s nested objects reflects in the other list’s nested objects.

org_list[2][0] = 'X' print('Inner List in Original: ', org_list[2], ' @', id(org_list[2])) print('Inner List in Shallow Copied: ', cpy_list[2], ' @', id(cpy_list[2]))
Inner List in Original: ['X', 'b', 'c'] @ 140532024760128 Inner List in Shallow Copied: ['X', 'b', 'c'] @ 140532024760128

What if we want a fully independent copy of a deeply nested list? In the next section, we’ll discuss how to perform a deep copy in Python.

The Python copy.deepcopy() Function

The copy.deepcopy() function recursively traverses a list to make copies of each of its nested objects. In other words, it makes a top-level copy of a list and then recursively adds copies of the nested objects from the original list into the new copy. This produces a fully independent copy from the original list, and any changes made to the nested objects of either will not be reflected in the other.

Like the copy.copy() function, the copy.deepcopy() function belongs to the copy module. Let’s try it out:

import copy org_list = [1, 2, ['a', 'b', 'c'], 3] cpy_list = copy.deepcopy(org_list) print('Original List: ', org_list, ' @', id(org_list)) print('Copied List: ', cpy_list, ' @', id(cpy_list))
Original List: [1, 2, ['a', 'b', 'c'], 3] @ 140532024761408 Copied List: [1, 2, ['a', 'b', 'c'], 3] @ 140532024405760

The output of the code above clearly shows that copy.deepcopy() has made a true copy of the original list, and even if we modify the inner list of the original list, it won’t be reflected in the deep copied list.

org_list[2][0] = 'X' print('Inner List in Original: ', org_list[2], ' @', id(org_list[2])) print('Inner List in Deep Copied: ', cpy_list[2], ' @', id(cpy_list[2]))
Inner List in Original: ['X', 'b', 'c'] @ 140532024404736 Inner List in Deep Copied: ['a', 'b', 'c'] @ 140532024405248

The code above shows that when we create a deep copy of a list, it also makes true copies of the nested objects. As mentioned earlier, the recursive deep copy produces a truly independent copy of the original list, which is why the inner lists in the original and copied lists point to two different memory locations. Obviously, any changes made to the inner list of one won’t be reflected in the other.

Conclusion

This tutorial discussed several different ways for copying a list in Python, such as the assignment operator, list slicing syntax, list.copy() , copy.copy() , and copy.deepcopy functions. Also, we discussed shallow and deep copies. I hope this tutorial helps you to better understand the different ways of copying lists in Python because they are critical to becoming a Pythonista.

About the author

Mehdi Lotfinejad

Mehdi is a Senior Data Engineer and Team Lead at ADA. He is a professional trainer who loves writing data analytics tutorials.

How to Clone a List in C#?

How to Clone a List in C#?

In this article, we will look at all the different ways we can clone a List in C# to another and what we should pay attention to when doing so.

To download the source code for this article, you can visit our GitHub repository.

In C# we have ample ways of doing that, so let’s dive right in.

How to Clone a List in C# That Contains Value Types

As we all love pizza, we are going to be cloning a list of toppings with all the methods in this section. Now, we are going to use a string in the example even though it is not a value type but a reference type. On the other hand, it is immutable and behaves as a value type, so we can use it in this section:

var toppings = new List < "Mozzarella", "Olive oil", "Basil" >;

Here, we define a toppings variable of List type, that holds the toppings for the classic Margherita pizza.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!

Become a patron at Patreon!

Next, we’ll look at the options for cloning the values of that List to another.

Using the List’s Constructor

One of the overloads of the List ‘s constructor takes in an IEnumerable :

var toppingsClonedWithConstructor = new List(toppings);

Here, we initialize a new toppingsClonedWithConstructor variable that contains the copied elements from our toppings list.

Using the List’s CopyTo Method

List has several methods that we can use to clone its contents to another list or collection.

One of those is the CopyTo method. The list inherits it from the ICollection interface and it can be used to clone the List to a T[] :

var toppingsClonedWithCopyTo = new string[toppings.Count]; toppings.CopyTo(toppingsClonedWithCopyTo);

First, we initialize a toppingsClonedWithCopyTo variable as a string[] that has a length equal to the length of the toppings list – hence the toppings.Count . Then we use the CopyTo method on the toppings list and pass the newly initialized array as a parameter. This way its contents are copied over to toppingsClonedWithCopyTo .

Using the List’s AddRange Method

Another method that takes in an IEnumerable as a parameter is the AddRange method:

var toppingsClonedWithAddRange = new List(); toppingsClonedWithAddRange.AddRange(toppings);

The AddRange method needs a List that is already initialized, so we declare the toppingsClonedWithAddRange variable and assign an empty List to it. Then we pass the toppings as a parameter to the AddRange method and it clones the contents for us.

Using the Enumerable’s ToList Method

The System.Linq namespace provides us with the Enumerable.ToList method:

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get paid? >> JOIN US! var toppingsClonedWithToList = toppings.ToList();

Here, we directly initialize our toppingsClonedWithToList variable by calling the ToList method on our already existing toppings variable, which clones its contents to our new list.

Alternatively, we can use the Enumerable.ToArray method in the same way if we want to clone the contents of a List to T[] .

Using the ConvertAll Method

List has another useful method that might look a bit daunting on the surface – this is the ConvertAll(Converter) method. It converts all the members of a list from one type to another and returns a list containing the converted members. We can even use it for cloning:

var toppingsClonedWithConvertAll = toppings .ConvertAll(new Converter(x => x));

We start by initializing a toppingsClonedWithConvertAll variable and assigning it the value returned from using the ConvertAll method on our toppings list. The method takes in a Converter , which is just a delegate for a method that converts an element from one type to another. It takes in the name of a method used for the conversion, or we can pass an anonymous method as well.

We don’t need a separate method to convert the element we pass in, so we simply use a lambda expression that returns the same value, hence the x => x .

Using the ICloneable Interface

A bit more complex way of cloning a List can be achieved using the ICloneable interface. But before we can use the interface’s Clone method, we need to set things up:

public class ToppingsList : List, ICloneable < public object Clone() < return this.MemberwiseClone(); >>

We create a generic ToppingsList class in a new file that inherits List and ICloneable . We also implement the Clone method by just returning the result of the Object ‘s (the ultimate base class in .NET) MemberwiseClone method which gives us a shallow copy of the object.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get paid? >> JOIN US! Program class:

var customToppingsList = new ToppingsList < "Mozzarella", "Olive oil", "Basil" >;

With this, we create a customToppingsList variable of our new generic type as ToppingsList and initialize it like a regular List .

Then we continue with:

var toppingsClonedWithICloneable = (ToppingsList)customToppingsList.Clone();

We declare a toppingsClonedWithICloneable variable and use the Clone method on our customToppingsList . We also cast the result to ToppingsList as the method itself returns an object .

To make sure that everything we have done to clone a List containing value types in C# works as intended, we can print all the results on the console:

Console.WriteLine("Original list: " + string.Join(", ", toppings)); Console.WriteLine("Cloned with Constructor: " + string.Join(", ", toppingsClonedWithConstructor)); Console.WriteLine("Cloned with CopyTo: " + string.Join(", ", toppingsClonedWithCopyTo)); Console.WriteLine("Cloned with AddRange: " + string.Join(", ", toppingsClonedWithAddRange)); Console.WriteLine("Cloned with ToList: " + string.Join(", ", toppingsClonedWithToList)); Console.WriteLine("Cloned with ConverAll: " + string.Join(", ", toppingsClonedWithConvertAll)); Console.WriteLine("Cloned with ICloneable: " + string.Join(", ", toppingsClonedWithICloneable));

And check the result:

Original list: Mozzarella, Olive oil, Basil Cloned with Constructor: Mozzarella, Olive oil, Basil Cloned with CopyTo: Mozzarella, Olive oil, Basil Cloned with AddRange: Mozzarella, Olive oil, Basil Cloned with ToList: Mozzarella, Olive oil, Basil Cloned with ConverAll: Mozzarella, Olive oil, Basil Cloned with ICloneable: Mozzarella, Olive oil, Basil

How to Clone a List in C# That Contains Reference Types

Reference type variables, unlike value type ones, store a reference to the data and not the data itself. This means that when we work with reference types, two variables can reference the same data – the downside here is that operations on one variable can affect the data referenced by another.

We are cloning lists, so we need one with reference types:

var pizzas = new List  < new Pizza < Name= "Margherita", Toppings = new List < "Mozzarella", "Olive oil", "Basil" >>, new Pizza < Name= "Diavola", Toppings = new List < "Mozzarella", "Ventricina", "Chili peppers" >> >;

Here we declare a pizzas variable of type List and add two pizzas to it.

Now, let’s look into the two types of copying we have when dealing with reference types.

Shallow Copy

We can easily achieve a shallow copy of our pizzas list with any of the methods from the previous section. But a shallow copy of a List , where T is a reference type, copies only the structure of the collection and references to its elements, not the elements themselves. This means that changes to the elements in any of the two lists will be reflected in both the original and copied lists.

Let’s illustrate this:

var clonedPizzas = pizzas.ToList(); var margherita = pizzas .FirstOrDefault(x => x.Name == "Margherita"); margherita.Toppings.Clear();

First, we create a clonedPizzas variable and clone the contents of pizzas to it using the ToList method (using any of the other methods used earlier will produce the same result). Then we get the Margherita pizza from the original list using the FirstOrDefault method. Finally, we use the Clear method to empty the list of Toppings for that pizza.

Now, let’s see what happens:

Console.WriteLine($"Original Margherita: "); Console.WriteLine($"Cloned with ToList: ");

We print the first pizza of each list to the console, which in both cases is the Margherita, using the First method.

We overrode the ToString method which will give us an easy-to-read representation of each pizza. Now, we can check the result:

Original Margherita: Pizza name: Margherita; Toppings: Cloned with ToList: Pizza name: Margherita; Toppings:

We can see that both the original and copied Margherita pizzas now have an empty list of Toppings . This is because when creating a shallow copy, we only clone the references to the objects, not the actual objects. This is not ideal because when we change elements in one list, we change the elements everywhere we have copied that list.

This might cause serious problems for us, so let’s what we can do to prevent it.

Deep Copy

The alternative is to create a deep copy – this means that we don’t just copy the references to the objects but create new, copied objects. This produces a different result than shallow copies as the objects referenced by the copied list are separate from those referenced in the original list.

Clone a List Using the ICloneable Interface

We can also use the Clone method we get from inheriting the ICloneable interface to create a deep copy.

Let’s do the necessary updates:

Then we get on with the cloning:

var pizzasClonedWithICloneable = new List(); foreach(var pizza in pizzas)

To do this we create a pizzasClonedWithICloneable variable as an empty List . Then, in a foreach loop iterating over our initial pizzas list, we get a new copy of the current pizza using the Clone method and add it to our new list.

Clone a List Using a Copy Constructor

A copy constructor is a constructor that takes an instance of the type as a parameter. Then the values of each property of that object are copied over to the newly created instance of that type:

public Pizza(Pizza pizza)

In our Pizza class, we create a new constructor that takes in a Pizza as a parameter. In it, we assign the Name and Toppings properties the values of the passed-in object, keeping in mind that we need to pass a copy of the Toppings , done with pizza.Toppings.ToList() , and not just assign the value.

Now, we can move back to our Program class and do the cloning:

var pizzasClonedWithCopyConstructor = new List(); foreach (var pizza in pizzas)

Similar to the ICloneable example, we create a new pizzasClonedWithCopyConstructor variable and initialize it with an empty List . Once this is done we create a foreach loop and on each iteration we use the copy constructor, new Pizza(pizza) , to add a copy of the current pizza to our new list.

Now, that we have used our two methods of creating a deep copy, let’s test them:

Original Margherita: Pizza name: Margherita; Toppings: Cloned with ICloneable: Pizza name: Margherita; Toppings: Mozzarella, Olive oil, Basil Cloned with Copy Constructor: Pizza name: Margherita; Toppings: Mozzarella, Olive oil, Basil

This time around we can see that our task to create a deep copy when trying to clone a List was successful and the cloned pizzas have their Toppings intact as we have indeed created a deep copy with both approaches.

Conclusion

In this article, we learned all about how to clone a List in C#. We also learned that shallow copies are easy to achieve in many ways and work wonders with value types but may cause headaches when used with reference types. Deep copies are very useful but tend to be more expensive than shallow ones, due to the need for additional object creation. It can also be very complicated to achieve if we deal with very complex objects. The good thing is that now you are prepared to tackle the cloning of List , no matter if the T is a value or a reference type.

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

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