Javatpoint Logo
Javatpoint Logo

How to convert an array to a list in python?

Using Python's tolist() function, you may turn an array into a list. Here is an example:

Output:

[1, 2, 3, 4, 5]

In this example, the array.array() constructor is used to create an array arr of type "i", which stands for integers. After that, the tolist() method is used to convert the array arr to a list lst. Finally, the type() function is used to verify that the resulting lst is indeed a list, and the print() function is used to display the contents of the list.

One way is to use list comprehension. A list comprehension is a concise way to create a new list by applying a function to each element of an existing list. Here is an example of using list comprehension to convert an array to a list:

Output:

[1, 2, 3, 4, 5]

In this example, the array arr is iterated over using for() loop, and each element x of the array is added to a new list lst using the list comprehension. Finally, the type() function is used to verify that the resulting lst is indeed a list, and the print() function is used to display the contents of the list.

The array's elements are not copied or duplicated. The list will instead make reference to the same entries as the initial array. It implies that altering the list will also alter the initial array. Here is an example to demonstrate this point:

Output:

array('i', [10, 2, 3, 4, 5])

In this example, the array arr is converted to a list lst using the tolist() method. After that, the first element of the list lst is modified to be 10. When you run the code, you can see that the original array arr has also been modified, as the first element of the array is now 10 as well.

If you want to create a completely separate list with the same elements as an array, you need to use the copy() method from the copy module. Here is an example:

Output:

array('i', [1, 2, 3, 4, 5])

In this example, the copy.copy() method is used to create a shallow copy of the array arr and assign it to the list lst. Now, when the first element of the list lst is modified to be 10, the original array arr is not affected.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA