Trending February 2024 # How To Copy A List In Python? (Why It Fails With Assignment) # Suggested March 2024 # Top 7 Popular

You are reading the article How To Copy A List In Python? (Why It Fails With Assignment) updated in February 2024 on the website Hatcungthantuong.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How To Copy A List In Python? (Why It Fails With Assignment)

In Python, copying a list can be unintuitive for beginners. This is because you cannot use the assignment operator to take an independent copy of a list. This can be confusing especially for beginner Pythonistas.

To create an independent copy of a list in Python, you need to use the copy module’s deepcopy() function like this:

import copy new_list = copy.deepcopy(old_list)

This comprehensive guide teaches you how to take an independent copy of a list in Python. You will also learn why doing it with an assignment operator doesn’t work.

The Problem with Copying Lists in Python

When dealing with Python variables, you can create a copy of a variable by assigning the existing variable to a new one.

For example:

a = 10 b = a

Now the variable b is a copy of variable a.

But if you copy a Python list in a similar fashion:

new_list = old_list

Any modifications made to the new_list also change the original list old_list.

It happens because new_list is actually not a copy of old_list. Instead, it is a reference to the same object in memory.

“Copying” a list just creates an alias for the same object in memory.

To create a completely independent copy of a list, use the copy module’s deepcopy() function.

import copy new_list = copy.deepcopy(old_list)

This is the only rational way to create a fully independent copy of a list in Python.

But if you don’t care about independent copies, there are many other ways to create a copy of a list in Python. These are:

copy() method. Creates a shallow copy.

[:] slicing operator. Creates a shallow copy.

list() function. Creates a shallow copy.

copy.copy() function. Creates a shallow copy.

copy.deepcopy() function. Creates a deep copy.

The following sections teach you how the assignment operator works, what is a shallow copy, and why copying “fails” with the assignment operator.

Assignment Operator (=) in Python

If you use the assignment operator (=) to copy a list in Python, you are not actually creating a copy of the object. Instead, you just give rise to a new variable that refers to the original list. The new variable is an alias to the original list.

Let’s see an example where we:

Create a list.

Assign or “copy” the list to a new variable.

Change the first number in the original list.

Print both lists.

And see what happens.

Here’s the code:

numbers = [1, 2, 3] new_numbers = numbers # Only change the original list numbers[0] = 100 print(numbers) print(new_numbers)

Output:

[100, 2, 3] [100, 2, 3]

Here you only changed the first element in the original numbers list. But this change also took place in the new_numbers list.

This happens because numbers and new_numbers are actually the very same list object.

Under the hood, both lists point to the same blob in memory.

Another way to verify this is by checking the memory address of these objects.

In Python, you can use the id() method to find out the memory address of any object.

Let’s check the memory addresses of both numbers and new_numbers.

print(id(numbers)) print(id(new_numbers))

Output:

140113161420416 140113161420416

The IDs are the same!

This verifies that the numbers and new_numbers are aliases pointing to the same list object in memory.

Think of the list object as a chunk of memory without a name. The numbers and new_numbers are just names via which you can access the list object in memory.

So when you create a new variable and assign a list object to it, you are introducing a new reference label to the original object.

To recap, the assignment operator (=) creates a new reference to an object in memory. It does not copy anything. This applies to lists as well as any other object in Python.

Next, let’s take a look at how you can actually copy list objects in Python.

The Copy Module in Python

As you learned, you cannot use the assignment operator to copy objects in Python. This is why there is a separate module, copy dedicated to copying Python objects.

The two key functions in the copy module are:

copy.copy()

copy.deepcopy()

Let’s take a look at what these functions do and what are the differences.

Shallow Copy: copy.copy()

In Python, a shallow copy can be created using copy.copy() function. A shallow copy solves our problem of copying a list in a way it does not depend on the original list.

For example:

import copy numbers = [1, 2, 3] # Independent copy of 'numbers' list new_numbers = copy.copy(numbers) numbers[0] = 100 print(numbers) print(new_numbers)

Output:

[100, 2, 3] [1, 2, 3]

As you can see, changing the first element in the original list did not change the copied list.

Let’s also verify the objects are not the same by using the id() function:

print(id(numbers)) print(id(new_numbers))

Output:

139764897739904 139764897692480

Horray! Now you know how to create a shallow copy of a list in Python. But mind the word shallow! It’s important to notice that sometimes you might deal with a list of lists.

In this case, the shallow copy does not behave the way you expect. Instead, it creates an independent copy of the outer list, but the inner lists are bound to the original list.

I know it sounds confusing.

Let me show what this means by running a simple experiment in which I:

Create a list of lists.

Create a shallow copy of the list.

Modify the first list’s first object.

import copy numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] new_numbers = copy.copy(numbers) numbers[0][0] = 1000 print(numbers) print(new_numbers)

Output:

[[1000, 2, 3], [4, 5, 6], [7, 8, 9]] [[1000, 2, 3], [4, 5, 6], [7, 8, 9]]

Here changing the first element of the first list affects the copied version of the list even though the new list should be a copy of the original one.

But why does this happen?

Let’s first compare the IDs of the lists to see if they are the same object:

print(id(numbers)) print(id(new_numbers))

Output:

140602923260928 140602923261632

Even the IDs do not match! This means new_numbers should be a true copy of numbers—and it is!

But why do the values still change in the copied list?

This is because copy.copy() creates a shallow copy.

This means the whole list is copied, but the lists inside the list are not. In other words, the inner lists refer to the lists in the original list.

I know this sounds strange, but this is how it works.

Let’s verify this by checking the IDs of the lists inside the list:

print(id(numbers[0]), id(numbers[1]), id(numbers[2])) print(id(new_numbers[0]), id(new_numbers[1]), id(new_numbers[2]))

Output:

140685291558208 140685291498496 140685291708160 140685291558208 140685291498496 140685291708160

As you can see, all the inner list IDs are the same.

So the outer list is copied but the inner lists are still bound to the original list of lists.

To put it together, here is an illustration of how copy.copy() works on a list of lists.

This highlights the behavior of shallow copying in Python.

As stated earlier, to create a completely independent copy, use the copy.deepcopy() function. Let’s take a closer look at this function to see what it does.

Deep Copy: copy.deepcopy()

Another key function in the copy module is the deepcopy() function.

This function creates a completely independent copy of a list or any other compound object in Python.

For example, let’s repeat the example in the previous chapter using deepcopy():

import copy numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] new_numbers = copy.deepcopy(numbers) numbers[0][0] = 1000 print(numbers) print(new_numbers)

Output:

[[1000, 2, 3], [4, 5, 6], [7, 8, 9]] [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

As you can see, changing the first element in the first list did not affect the copied list.

In other words, you have successfully created a completely independent copy of the original list.

No part in the deep-copied list points to the original list. Thus, a deep copy creates a truly independent copy.

I recommend you play with the examples to learn what is happening truly.

Copying a Number Object in Python

This guide would not be complete if we did not talk about copying other objects than lists. It is important to realize everything related to copying lists applies to copying any other Python object.

Let’s repeat the very first example in this guide using integers instead of lists.

In other words, let’s:

Create a number variable.

Copy the number to another variable using the assignment operator.

Change the original number.

See what happens to the copy.

a = 10 b = a a = 50 print(a, b)

Output:

50 10

As you can see, changing the original number a did not change the number b. This is probably something you would expect.

But this contradicts what we said earlier about copying Python objects: A Python object cannot be copied using the assignment operator.

However, looking at the above example, it seems b is an independent copy of a because changing a does not change b.

Even though this happens, b is not a copy of a. This is important to understand. You can verify this by checking the IDs of the variables before changing the value in a.

a = 10 b = a print(id(a)) print(id(b))

Output:

9789280 9789280

As you can see, the IDs match. In other words, a and b are both aliases to the same integer object in memory.

But why does changing a not change b then?

It all boils down to mutability.

First of all, you need to recall that a variable is just a label via which you can access an object that lives somewhere in memory. So if you change the value of a variable, you aren’t actually changing the variable itself, but the object in memory that it refers to.

In Python, integer objects are immutable. Immutability means you cannot make direct changes to integer objects. If you assign a new integer to a variable, you create a new integer object in memory and set the existing variable point to that new memory address.

On the other hand, a list is a mutable object. This means you can change the list object directly. So if you assign an existing list to a new variable, you are making the new variable point to the original list.

This describes Python mutability in a nutshell.

Now, let’s go back to the example of copying an integer. Let’s print the IDs of the variables before and after changing the value in a:

a = 10 b = a print(f"Before assignment id(a) = {id(a)}, id(b) = {id(b)}") a = 50 print(f"After assignment id(a) = {id(a)}, id(b) = {id(b)}")

Output:

Before assignment id(a) = 9789280, id(b) = 9789280 After assignment id(a) = 9790560, id(b) = 9789280

The IDs of variables a and b match before assigning a new value to a but not afterward.

In other words, before changing the value in a:

a and b point to the same integer object in memory.

And after changing the value in a:

a points to a new integer object in memory but b still points to where a used to point.

So after assigning a new value to variable a, it points to a new integer object in memory. This happens because of immutability. The integer object 10 cannot directly change. Instead, a new integer object needs to be created.

Here is a quick illustration of how the code works:

Assigning a new integer to a creates a new integer object where the variable a points to.

To recap, the assignment operator (=) cannot be used to copy objects in Python. However, when dealing with immutable objects, it looks as if this was the case. But it is not.

If someone tells you to copy a variable, technically you need to use copy.copy() or copy.deepcopy() instead of the assignment operator.

However, when dealing with immutable objects, this is unnecessary, as the behavior is the same regardless of whether you used copy module or assignment operator.

But with mutable objects, you need to use the copy module to create a real copy of the object.

At this point, you understand why the assignment operator does not copy objects in Python. You also learned how to use the copy module to create copies of Python objects.

Now that you understand what is a shallow copy and a deep copy, let’s put it all together by taking a look at 5 common ways to copy a list in Python.

5 Ways to Copy a List in Python

There are five main ways to copy a list in Python:

Let’s see examples of each of these

1. The copy() Method

As of Python 3.3, a list comes with a built-in copy() method. This method creates a shallow copy of the list.

For example:

numbers = [1, 2, 3] new_numbers = numbers.copy() print(numbers) print(new_numbers)

Output:

[1, 2, 3] [1, 2, 3] 2. The [:] Slicing operator

In Python, slicing means pulling a range of values from an iterable, such as a list.

Slicing goes with the syntax of:

iterable[start:end]

Where start specifies the starting index and end specifies the ending index.

If you do not specify the start parameter, slicing starts from the very first element. If you do not specify the end, the slicing ends at the very last element.

Calling iterable[:] returns a slice that represents the whole iterable. In other words, it returns a copy of a list when called on a list.

Notice that this also creates a shallow copy.

For instance:

numbers = [1, 2, 3] new_numbers = numbers[:] print(numbers) print(new_numbers)

Output:

[1, 2, 3] [1, 2, 3] 3. The list() Function

To convert an object to a list in Python, you can use the built-in list() function. This function creates a new list object for the input argument.

When you call the list() function on a list in Python, you force it to create a copy of the original list. The type of this copy is also shallow.

For instance:

numbers = [1, 2, 3] new_numbers = list(numbers) print(numbers) print(new_numbers)

Output:

[1, 2, 3] [1, 2, 3] 4. The copy.copy() Function

As discussed earlier in this guide, there is a dedicated module copy for copying Python objects.

One of the functions in this module is the copy() function. This function creates a shallow copy of a Python object. You can use copy.copy() to create a copy of a list.

For instance:

import copy numbers = [1, 2, 3] new_numbers = copy.copy(numbers) print(numbers) print(new_numbers)

Output:

[1, 2, 3] [1, 2, 3] 5. The copy.deepcopy() Function

The only way to create a truly independent deep copy of a Python object is by using the copy.deepcopy() function.

The difference between a shallow copy and a deep copy is only relevant to objects that consist of objects. This is comprehensively explained earlier in this guide.

You can use copy.deepcopy() to create a deep copy of a list.

For example:

import copy numbers = [1, 2, 3] new_numbers = copy.deepcopy(numbers) print(numbers) print(new_numbers)

Output:

[1, 2, 3] [1, 2, 3] Conclusion

Today you learned how to copy a Python list successfully.

To recap, copying using the assignment operator is not possible. Instead of copying, it creates a new alias to the original object. This means changing the original object changes the “copy” as well.

To truly copy an object in Python, use the copy module’s functions:

copy.copy() for a shallow copy where compound objects are bound to the original object.

copy.deepcopy() for a deep and completely independent copy.

Further Reading

Python Interview Questions

Best Websites to Learn Python

You're reading How To Copy A List In Python? (Why It Fails With Assignment)

How To Copy A File In Python: Shutil.copy()

To copy a file in Python, use the shutil module’s copyfile() function.

from shutil import copyfile copyfile(src, dst)

This piece of code copies the contents of the file src to a destination file dst.

Both src and dst are strings that represent the names of the files (or rather, paths to the files).

If a file dst does not exist, a new file is created. If it does, the file behind that path is overridden.

Real-Life Example of How to Copy a File with Python

To understand how to copy a file in Python, you need to see an example.

Let’s start with a setup like this, where you have two files chúng tôi and chúng tôi in the same folder on your computer:

The chúng tôi is a program that copies the file called chúng tôi to a new file called chúng tôi .

Because you are working in the same folder, you do not need to worry about the full paths of the files.

All you need is the names of the files.

Here is the code:

from shutil import copyfile src = 'Example1.txt' dst = 'Example2.txt' copyfile(src, dst)

After running this piece of code, you should see a file called chúng tôi appear in the same folder:

This is how easy it is to copy a file using Python.

How to Copy a File to Different Folder

More often than not your files are not going to be in the same folder.

If this is the case, accessing the files with their names is not possible.

If you want to copy a file from one folder to another, you need to specify the path of the source and the destination.

The path obviously depends entirely on your file setup.

Let’s see a simple and demonstrative example.

Let’s say you have a folder called Project. Inside this folder, you have three subfolders called Scripts, Images, and Favorites.

Inside the Scripts folder, you have a file called chúng tôi . This is a program file that copies an image called chúng tôi from Images to Favorites.

Here is an illustration of the folder structure:

Because the code file, the source file, and the destination all lie in different folders, you need to work with paths instead of file names.

Here is how the chúng tôi file looks in the Scripts folder

from shutil import copyfile src = '../Images/zebra.png' dst = '../Favorites/zebra.png' copyfile(src, dst)

Let’s examine the paths to understand how they work.

The ../ refers to the parent folder. In the case of the Scripts folder, this refers to the Project folder in which the Images and Favorites folders live.

The parent folder has to be specified because otherwise, the chúng tôi script would search inside the Scripts folder which has no other files except for the code file.

Inside the Project folder, accessing the subfolders Images and Favorites is trivial:

Images/zebra.png is the path to the image.

Favorites/zebra.png is the desired path to the copied file.

Conclusion

Today you learned how to copy a file in Python using the shutil module’s copyfile() function:

from shutil import copyfile copyfile(src, dst)

Where:

src is the path of the file to be copied as a string.

dst is the destination file’s path as a string.

In case the source file and the destination file lie in the same folder, it is enough to use the names of the files.

Thanks for reading. Happy coding!

Further Reading

How to Read a Text File in Python

Python Interview Questions

How To List, Create Python Directory

Introduction to Python Directories

Python directory is defined as a list of folders, files of different types like a tree structure having sub-directories inside the directory and files inside the sub-directories, as we have too many files and directories python directory will come to rescue in managing the files, directories, and sub-directories is called python directory. Python has an OS module that will help manage, create, remove, read and write directories, files, etc. Using it, we can perform many operations using OS modules like creating a directory, getting the current location of a directory, rename a directory, changing the directory, etc.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How to Create Python Directory?

In Python, Python directory can be created using the OS module and using its function mkdir() in python as below:

Syntax:

os.mkdir('name of the directory')

The directory name’s name is the directory name that will be created in the current working directory location.

Let us create a directory called “repository” in the current working location and another directory called “sdk” in a specific location in the following examples.

Code:

import os os.mkdir('repository') os.mkdir('C:/Users/lenovo/PycharmProjects/sdk')

In the above example, we have imported the os module and using the function mkdir() to create the directory ‘repository’. In another statement, we are creating a directory “sdk” at location ‘C:/Users/lenovo/PycharmProjects’. We need to use forward slash ‘/’ while creating a directory in other locations.

Output:

We will see the list of directories available in the current working directory as below:

Now we will see the output of directories available in the current working directory after the creation of the above directories in the example and output as below:

In the above output, we can able to see the new directories ‘repository’ and ‘sdk’, which we created in the above example.

How to List Python Directories?

In python, directories at any given location can be listed using the OS module, which has many functions and to list is listdir() function.

Syntax:

The syntax to list python directories is as below:

os.listdir()

or

os.listdir('path')

The above command will list all directories in the current working directory, and another syntax will take the path as an argument and list all the directories in that path.

Example:

Let us create an example to list all the directories present in the current working directory that is

“C:/Users/lenovo/PycharmProjects/projman” and using the path same as a current working directory as below:

Code:

import os os.listdir() os.listdir('C:/Users/lenovo/PycharmProjects/projman')

In the above example, we have imported the OS module and using its function listdir() to see the list of available directories in the current working directory and whereas in another example, we are passing path “C:/Users/lenovo/PycharmProjects/projman” to the listdir() function so that it will list available directories in that particular path.

Output:

In the above example, we have executed the os.listdir() function in the current working directory, and the list of directories are ‘Programming’, ‘projman’, ‘projman.rar’,’pycharmprojects’,’repository’, and ‘sdk’.

In the above example, we have given a path to the os.listdir() function and lists all the available directories in that path as ‘.idea’,’Approach’,’build’, ’Makefile’,’README.md’, and ’src’.

How to Create Temporary Python Directories?

In python, we can create the temporary directory using the tempfile module and the function TemporaryDirectory() as below:

Syntax:

The syntax to create the Temporary Directory in python is as below:

import tempfile tempfile.TemporaryDirectory() or tempfile.TemporaryDirectory(dir='path')

In the above syntax, we have imported the module tempfile and using the function TemporaryDirectory() to create a temp directory in the temp directory, and we can pass the path where it needs to create the temporary directory in the second syntax.

Example:

Let’s create an example to create a temporary directory in the temp location and another temporary directory by giving a location as below:

Code:

import tempfile f = tempfile.TemporaryDirectory() f.name

Output:

In the above example, we have imported the tempfile module and created a temporary directory using TemporaryDirectory() function, and to check the temporary directory name, we have used file pointer.“name”, which gives the location of the file with the name as in the above output.

Code:

import tempfile tempfile.TemporaryDirectory(dir ='C:/Users/Lenovo/PycharmProjects')

In the above example, we have imported the tempfile module and explicitly gave the path ‘C:/Users/lenovo/PycharmProjects’ to create the temp file.

Output:

We can observe the temporary file name in the location or path that we have provided the TemporaryDirectory() function in the above output. If we use file pointer, then we need to use chúng tôi otherwise, by default, it will display the temporary file location after creation.

How to Write your Own Python Directories?

In python, we can create our own directories apart from the final directory using the OS module and its function makedirs(), which will create our own directories mentioned in the path.

Syntax:

The syntax to create own python directories is as below:

import os os.makedirs('path')

In the above syntax, we have imported the module OS and using its function mkdirs() with a path that will have a list of directories to be created on its own.

Example:

Let’s create an example to create its own directories based on the path given “sdk/repos/hello” in the current working directory as below:

Code:

import os os.makedirs("sdk/repos/hello")

In the above example, we have imported the OS module and using its function makedirs() to create directories on its own based on the path “sdk/repos/hello” apart from creating “sdk” it will create folders “repos”, “hello” on its own.

Output:

In the above output, we can see the directories created on their own after executing the example can be seen as “sdk”, “repos”, and “hello”.

Advantages of Python Directories

By using python directories, we can manage a large number of files and directories easily.

Python modules OS and tempfile provide different functions to apply to python directories.

They are easy to use and understand.

It provides an efficient way of handling file systems in python.

Conclusion Recommended Articles

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

How To Copy Files From One Folder To Another Using Python?

A file is a collection of information or data that is stored on a computer. You are already familiar with several file types, such as your audio, video, and text files.

Text files and binary files are the two categories into which we often split files. Simple text is contained in text files, as opposed to binary data, which can only be read by computers.

A group of files and subdirectories is called a directory or folder. A subdirectory is a directory present inside a directory. Numerous operating system functions can be carried out automatically.

File Operations Using Python

Python provides various methods to perform operations on the files and folders of the underlying operating system.

The OS module in Python has functions for adding and deleting folders, retrieving their contents, changing the directory, locating the current directory, and more. Import this module, we will use the listdir() method of it to fetch the files.

Similarly, the shutil module provides a number of functions for dealing with operations on files and associated collections. It gives users the option to copy and delete files. You can copy the contents of one folder to another using the shutil.copy(), shutil.copy2() and shutil.copytree() methods of this module.

You can include these functions in your file by importing their respective modules as shown below −

import

shutil shutil

.

submodule_name

(

arguments passed

)

Using shutil.copy() operation

Using this function, the text or content of the source file is copied to the target file or directories. Additionally, the permission mode of the file is preserved, but the file metadata (such as the “Date Creation”, “Date Modification” etc..) is not preserved.

Syntax

Following is the syntax of the shutil.copy() method−

shutil.copy(origin, target)

where

Origin − A string containing the source file’s location or path

Target − A string containing the destination file’s location or path.

Example

Following is an example of to copy files from one folder to other using shutil.copy() operation −

import

os

import

shutil files

=

os

.

listdir

(

origin

)

for

file_name

in

files

:

shutil

.

copy

(

origin

+

file_name

,

target

+

file_name

)

print

(

"Files are copied successfully"

)

Output

Following is an output of the above query:

Files are copied successfully

Note − Both a relative and an absolute path can be used to copy a file. The file’s location on the disc is indicated by the path

Here we are providing the folder path of both the source and the destination of the files.

Using shutil.copy2() operation

First of all, this function is exactly like copy() with the exception that it keeps track of the source file’s metadata.

The execution program for this is exact same as shutil.copy(). The only difference is that while fetching the file to directory, in place of shutil.copy() we write shutil.copy2().

shutil

.

copy2

(

origin

+

file_name

,

target

+

file_name

)

Syntax

Following is the syntax of the shutil.copy2() method –

shutil.copy2(origin, target)

Origin and target values are same as defined above.

The copy2() function in this code does one additional operation in addition to a copy() which is to keep the metadata.

Using shutil.copytree() method

This function moves a file and any subdirectories it contains from one directory to another.

This indicates that both the source and the destination include the file. The string must contain the names of both parameters.

Syntax

Following is the syntax of the shutil.copytree() method –

shutil.copytree(origin, target)

Origin and target values are same as defined above.

Example

Following is an example of to copy files from one folder to other using shutil.copytree() operation:

import

shutil

print

(

"File Copied Successfully"

)

Output

Following is an output of the above query:

File Copied Successfully

As an output we will be able to see the changes made after the execution i.e. the ‘Works’ folder gets copied to the ‘Works TP’ folder with the name of ‘newfolder’ as assigned in the code above containing all the files inside it which was there in the Works folder.

In order to obtain a duplicate of that file, we have included the copytree() function in this code.

Python How To Split A List To N Chunks Of Even Size

To split a list into N chunks in Python, you can use iterators:

def split_list(lst, chunk_size): for i in range(0, len(lst), chunk_size): yield lst[i:i+chunk_size] # Example use lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunk_size = 3 for chunk in split_list(lst, chunk_size): print(chunk)

Notice that it isn’t always possible to produce a list where the chunks are equal in length. This is because the list elements might not be evenly divisible to the N chunks.

This is a comprehensive guide to splitting a list into N chunks in Python. In case you’re looking for a quick solution, I’m sure the above will do. But if you’re learning Python, make sure to read the entire guide to figure out multiple approaches to splitting lists into chunks. The idea of this guide is not to use an existing solution but to implement the logic yourself.

Let’s jump into it!

1. Iterator Approach

Here is an example of how to split a Python list into equally-sized chunks using iterators and the yield keyword:

def split_list(lst, chunk_size): for i in range(0, len(lst), chunk_size): yield lst[i:i+chunk_size] # Example usage lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunk_size = 3 for chunk in split_list(lst, chunk_size): print(chunk)

This code will output the following:

[1, 2, 3] [4, 5, 6] [7, 8, 9]

Let’s take a closer look at the code.

The split_list function takes two arguments: a list lst and an integer chunk_size that specifies the size of each chunk. The function uses a for loop to iterate over the list, and yields a sublist of lst starting at the current index and ending at the current index plus the chunk size.

Here’s a step-by-step explanation of how the code works:

The split_list function is called with a list lst and a chunk size chunk_size.

The for loop iterates over the list, starting at index 0 and incrementing the index by chunk_size each time. For example, if the chunk size is 3, the first iteration will start at index 0, the second iteration will start at index 3, the third at 6, and so on.

On each iteration, the yield keyword constructs a sublist of lst starting at the current index and ending at the current index plus the chunk size. E.g. if the current index is 0 and the chunk size is 3, the sublist will be lst[0:3], which is the three elements of lst.

The for loop in the example code then iterates over the chunks yielded by split_list and prints each chunk.

The result of all of this is a list that is split into N chunks.

But What On Earth Does the ‘yield’ Do?

The previously introduced approach is the easiest one to split a list into chunks. But if you’re new to the yield keyword and iterators, this solution might just leave you confused.

In case you’re interested in iterators, make sure to read this complete guide to iterators and iterables in Python.

The next section teaches you how to do the previous approach without using the yield keyword but using lists instead.

2. For Loop Approach

Here’s another way to split lists into chunks in Python. This approach uses for loops and lists and is thus a bit more beginner-friendly than the previous example.

Here are the steps you need to take:

Determine the number of chunks you want to split the list into. Let’s call this number n.

Floor-divide the length of the list by n to find the size of each chunk (floor division rounds down so that the chunk size isn’t e.g. 3.3333 but instead just 3). We’ll call this number chunk_size.

Use the range() function to create a list of numbers that specify the indexes where each chunk should start. If the original list has 10 elements and you want to split it into 3 chunks, the list of starting indexes would be [0, 3, 6].

Use a for loop to iterate over the list of starting indexes, and use the list[start:end] syntax to extract each chunk from the original list.

# Set the number of chunks N = 4 # Create a list of numbers my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Create an empty list to store the chunks chunks = [] # Iterate over the elements of the list in groups of N for i in range(0, len(my_list), N): # Extract each group of N elements as a sublist chunk = my_list[i:i + N] # Append the sublist to the list of chunks chunks.append(chunk) # Print the chunks print(chunks)

This code produces the following output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]] 2.1. List Comprehensions Can Do the Same

When you’re dealing with for loops, in some cases, you might be able to use a list comprehension to tidy up the code.

It’s always up for debate as to whether you should use comprehension or not. This is because a list comprehension for sure shortens the code but might actually make it less readable.

Anyway, here’s the previous example that uses a list comprehension instead of a for loop:

# Define the input list input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Define the chunk size chunk_size = 3 # Create the output list using a list comprehension output_list = [input_list[i:i + chunk_size] for i in range(0, len(input_list), chunk_size)] # Print the output list print(output_list)

This will produce the following output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] 3. While Loop

In the previous examples, you used a for loop to split a list into chunks. Because you can use a for loop, you can certainly do one with a while loop too!

Here’s what the code looks like when using a while loop:

# define the list of elements my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # define the size of the chunks chunk_size = 3 # create an empty list to store the chunks chunks = [] # create an index variable to track the current position in the list index = 0 # loop until the index is larger than the length of the list while index < len(my_list): # get the sublist of the current chunk chunk = my_list[index:index+chunk_size] # append the chunk to the list of chunks chunks.append(chunk) # update the index to the next chunk index += chunk_size # print the resulting chunks print(chunks)

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

This solution creates an empty list to store the resulting chunks and then uses a while loop to iterate over the original list by chunk sizes, appending each chunk to the list of chunks. The index variable is used to track the current position in the list and is updated at each iteration to the next chunk.

4. Use NumPy to Split into N Chunks

In Python, there’s a popular math and science module called NumPy that the scientific Python community uses a lot.

If you’re using NumPy already, you can use the array_split() function to split lists into chunks. This function takes in the list as the first argument and the size of the chunks as the second argument.

Notice that this approach forces the elements into N chunks. The leftover values aren’t placed in their own chunk but are pushed to the last chunk instead.

For example, let’s split a list of 10 numbers into 3 chunks:

import numpy as np # Define the list to be split my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Split the list into chunks of size 3 chunks = np.array_split(my_list, 3) # Print the resulting chunks print(chunks) # Output: [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9, 10])]

Notice how the last chunk now has 4 elements instead of taking the extra element and placing it in its own chunk.

Thanks for reading. Happy coding!

Read Also

Comprehensions in Python

How To Implement Endless List With Recyclerview In Android?

This example demonstrates how do I implement an endless list with RecyclerView in android.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Add the following dependency in build gradle (Module app) −

implementation 'com.android.support:cardview-v7:28.0.0'    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    <androidx.recyclerview.widget.RecyclerView       android:id="@+id/recyclerView"       android:layout_width="match_parent" import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.os.Handler; import java.util.ArrayList; public class MainActivity extends AppCompatActivity {    RecyclerView recyclerView;    RecyclerViewAdapter recyclerViewAdapter;    boolean isLoading = false;    @Override    protected void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       setContentView(R.layout.activity_main);       recyclerView = findViewById(R.id.recyclerView);       populateData();       initAdapter();       initScrollListener();    }    private void populateData() {       for (int i = 0; i < 10; i++) {          rowsArrayList.add("Number " + i);       }    }    private void initAdapter() {       recyclerViewAdapter = new RecyclerViewAdapter(rowsArrayList);       recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));       recyclerView.setAdapter(recyclerViewAdapter);    }    private void initScrollListener() {       recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {          @Override          public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {             super.onScrollStateChanged(recyclerView, newState);          }          @Override          public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {             super.onScrolled(recyclerView, dx, dy);             LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();             if (!isLoading) {                if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == rowsArrayList.size() - 1) {                                     loadMore();                   isLoading = true;                }             }          }       });    }    private void loadMore() {       rowsArrayList.add(null);       recyclerViewAdapter.notifyItemInserted(rowsArrayList.size() - 1);       Handler handler = new Handler();       handler.postDelayed(new Runnable() {          @Override          public void run() {             rowsArrayList.remove(rowsArrayList.size() - 1);             int scrollPosition = rowsArrayList.size();             recyclerViewAdapter.notifyItemRemoved(scrollPosition);             int currentSize = scrollPosition;             int nextLimit = currentSize + 10;             while (currentSize - 1 < nextLimit) {                rowsArrayList.add("Number " + currentSize);                currentSize++;             }             recyclerViewAdapter.notifyDataSetChanged();             isLoading = false;          }       }, 2000);    } import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class RecyclerViewAdapter extends    private final int VIEW_TYPE_ITEM = 0;       mItemList = itemList;    }    @NonNull    @Override    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {       if (viewType == VIEW_TYPE_ITEM) {          View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);          return new ItemViewHolder(view);       } else {          View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading, parent, false);          return new LoadingViewHolder(view);       }    }    @Override    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {       if (viewHolder instanceof ItemViewHolder) {          populateItemRows((ItemViewHolder) viewHolder, position);       }        else if (viewHolder instanceof LoadingViewHolder) {          showLoadingView((LoadingViewHolder) viewHolder, position);       }    }    @Override    public int getItemCount() {       return mItemList == null ? 0 : mItemList.size();    }    @Override    public int getItemViewType(int position) {       int VIEW_TYPE_LOADING = 1;       return mItemList.get(position) == null ? VIEW_TYPE_LOADING :       VIEW_TYPE_ITEM;    }    private class ItemViewHolder extends RecyclerView.ViewHolder {       TextView tvItem;       ItemViewHolder(@NonNull View itemView) {          super(itemView);          tvItem = itemView.findViewById(R.id.textViewItem);       }    }    private class LoadingViewHolder extends RecyclerView.ViewHolder {       ProgressBar progressBar;       LoadingViewHolder(@NonNull View itemView) {          super(itemView);          progressBar = itemView.findViewById(R.id.progressBar);       }    }    private void showLoadingView(LoadingViewHolder viewHolder, int position) {    }    private void populateItemRows(ItemViewHolder viewHolder, int position) {       String item = mItemList.get(position);       viewHolder.tvItem.setText(item);    } <androidx.cardview.widget.CardView    android:layout_width="match_parent"    android:layout_height="wrap_content"    app:cardElevation="2dp"    <TextView       android:id="@+id/textViewItem"       android:layout_width="match_parent"       android:layout_height="wrap_content"    android:layout_width="match_parent"    android:layout_height="match_parent"    <ProgressBar       android:id="@+id/progressBar"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:layout_gravity="center_horizontal"       android:indeterminate="true"       android:paddingLeft="8dp"    <application       android:allowBackup="true"       android:icon="@mipmap/ic_launcher"       android:label="@string/app_name"       android:roundIcon="@mipmap/ic_launcher_round"       android:supportsRtl="true"

Update the detailed information about How To Copy A List In Python? (Why It Fails With Assignment) on the Hatcungthantuong.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!