Difference between list and array python

Difference between List and Array in Python

In Python, lists and arrays are the data structures that are used to store multiple items. They both support the indexing of elements to access them, slicing, and iterating over the elements. In this article, we will see the difference between the two.

Operations Difference in Lists and Arrays

Accessing element is fast in Python Arrays because they are in a contiguous manner but insertion and deletion is quite expensive because all the elements are shifted from the position of inserting and deleting element linearly. Suppose the array is of 1000 length and we are inserting/deleting elements at 100 position then all the elements after the hundred position will get shifted due to which the operation becomes expensive.

Accessing an element in a Python List takes linear time because all the elements in the lists are linked with each other for accessing ith element we have to traverse all the previous elements in a list however insertion and deletion in a list take constant(which is not expensive at all) time as all the elements are linked with each other for adding or removing new element we just remove the linked between the element and link new element like plumbing the pipe there is no need to shift element as in arrays.

Читайте также:  Sqlalchemy python delete all

In the case of the Binary Search Algorithm Arrays take log(n) time but the list may take extra time because accessing the mid element does not take constant time like an array.

What are Lists?

A list in Python is an inbuilt collection of items that can contain elements of multiple data types, which may be either numeric, character logical values, etc. It is an ordered collection supporting negative indexing. A list can be created using [] containing data values. Contents of lists can be easily merged and copied using Python’s inbuilt functions.

Example:

In this example, we are creating a list in Python . The first element of the list is an integer, the second a Python string , and the third is a list of characters.

Источник

Array vs. List in Python – What’s the Difference?

Both lists and arrays are used to store data in Python. Moreover, both data structures allow indexing, slicing, and iterating. So what’s the difference between an array and a list in Python? In this article, we’ll explain in detail when to use a Python array vs. a list.

Python has lots of different data structures with different features and functions. Its built-in data structures include lists, tuples, sets, and dictionaries. However, this is not an exhaustive list of the data structures available in Python. Some additional data structures can be imported from different modules or packages.

An array data structure belongs to the «must-import» category. To use an array in Python, you’ll need to import this data structure from the NumPy package or the array module.

And that’s the first difference between lists and arrays. Before diving deeper into the differences between these two data structures, let’s review the features and functions of lists and arrays.

What Is a List in Python?

A list is a data structure that’s built into Python and holds a collection of items. Lists have a number of important characteristics:

  • List items are enclosed in square brackets, like this [item1, item2, item3].
  • Lists are ordered – i.e. the items in the list appear in a specific order. This enables us to use an index to access to any item.
  • Lists are mutable, which means you can add or remove items after a list’s creation.
  • List elements do not need to be unique. Item duplication is possible, as each element has its own distinct place and can be accessed separately through the index.
  • Elements can be of different data types: you can combine strings, integers, and objects in the same list.

Lists are very easily created in Python:

list = [3, 6, 9, 12] print(list) print(type(list))

Python lists are used just about everywhere, as they are a great tool for saving a sequence of items and iterating over it.

What Is an Array in Python?

An array is also a data structure that stores a collection of items. Like lists, arrays are ordered, mutable, enclosed in square brackets, and able to store non-unique items.

But when it comes to the array’s ability to store different data types, the answer is not as straightforward. It depends on the kind of array used.

To use arrays in Python, you need to import either an array module or a NumPy package.

The Python array module requires all array elements to be of the same type. Moreover, to create an array, you’ll need to specify a value type. In the code below, the «i» signifies that all elements in array_1 are integers:

array_1 = arr.array("i", [3, 6, 9, 12]) print(array_1) print(type(array_1))

On the other hand, NumPy arrays support different data types. To create a NumPy array, you only need to specify the items (enclosed in square brackets, of course):

array_2 = np.array(["numbers", 3, 6, 9, 12]) print (array_2) print(type(array_2))

As you can see, array_2 contains one item of the string type (i.e., «numbers») and four integers.

So What’s the Difference?

Now that we know their definitions and features, we can talk about the differences between lists and arrays in Python:

  • Arrays need to be declared. Lists don’t, since they are built into Python. In the examples above, you saw that lists are created by simply enclosing a sequence of elements into square brackets. Creating an array, on the other hand, requires a specific function from either the array module (i.e., array.array()) or NumPy package (i.e., numpy.array()). Because of this, lists are used more often than arrays.
  • Arrays can store data very compactly and are more efficient for storing large amounts of data.
  • Arrays are great for numerical operations; lists cannot directly handle math operations. For example, you can divide each element of an array by the same number with just one line of code. If you try the same with a list, you’ll get an error.
array = np.array([3, 6, 9, 12]) division = array/3 print(division) print (type(division))
list = [3, 6, 9, 12] division = list/3
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () 1 list = [3, 6, 9, 12] ----> 2 division = list/3 TypeError: unsupported operand type(s) for /: 'list' and 'int'

Of course, it’s possible to do a mathematical operation with a list, but it’s much less efficient:

Code Editor

So, when should you use a list and when should you use an array?

  • If you need to store a relatively short sequence of items and you don’t plan to do any mathematical operations with it, a list is the preferred choice. This data structure will allow you to store an ordered, mutable, and indexed sequence of items without importing any additional modules or packages.
  • If you have a very long sequence of items, consider using an array. This structure offers more efficient data storage.
  • If you plan to do any numerical operations with your combination of items, use an array. Data analytics and data science rely heavily on (mostly NumPy) arrays.

Time to Practice Python Arrays and Lists!

Great! Now you know the difference between an array and a list in Python. You also know which to choose for a sequence of items. Now it’s time to practice!

If you want to advance your understanding of data structures and practice 100+ interactive exercises, check out the LearnPython.com course Python Data Structures in Practice. It will help you feel like a pro when dealing with lists, nested lists, tuples, sets, and dictionaries.

Источник

What is the Difference between Array and List in Python?

Python Certification Course: Master the essentials

List and array are among the data structures that python supports for storing the elements.

Python List:

  • Lists are the inbuilt data structure of python.
  • We can store elements of different types in the list.
  • Items in the list are enclosed between square brackets and separated by commas.
  • We can even nest lists with other data structures like lists, dictionaries, tuples, etc.

Python Array:

  • Arrays are not the in-built data structure readily available in Python.
  • We must import the array from the ‘array’ or ‘numpy’ module.
  • Array stores elements of similar types. If we try to store elements of different types, it will throw an error.
  • We can only store elements of the same types in the array.

Examples of List and Array

Let’s understand the differences between a list and an array in python by looking at basic examples of list and array.

Python List:

In the above example, we have created sample_list, which contains values of different types, and sample_nested_list contains the nested lists in itself, which are of different sizes, and also it contains numeric values as well.

Python Array:

Method 1: Using array package

Method 2: Using numpy package

In the above example, we have created the sample_array using two different methods. Method 1 uses the array package to initialize the sample array, whereas method 2 uses the numpy package to initialize the sample array. sample_array won’t be able to store elements of different data types. If we try to add some string value in the sample array, it will throw an error. Also, we will not be able to have the nesting of arrays if the arrays are of different sizes, which is not the case with the list.

Array vs List in Python:

List Array
In-built data structure Need to import using array or numpy
Enclosed in square brackets need to enclose using .array function
Can contain elements of different types Cannot contain elements of different types
Variable size nesting is possible Need to have the same size of the array for nesting.
Cannot apply direct arithmetic operations Can apply direct arithmetic operations.
It consumes more memory It consumes less memory comparatively
Can be printed without creating an explicit loop Need to create an explicit loop to print the array elements.

Learn More:

Want to learn more about arrays and lists in python?

Conclusion:

  • List is an in-built data structure, whereas, for an array, we need to import it from the array or numpy package.
  • Lists and arrays both are mutable and store ordered items.
  • List can store elements of different types, but arrays can store elements only of the same type.
  • List provides more flexibility as it doesn’t require explicit looping, but arrays require explicit looping to print elements.
  • We can’t apply arithmetic operations directly in the list, but we can apply arithmetic operations directly on arrays.

Источник

Оцените статью