Python List vs Array


Gaming Laptop Series

Like in many other programming languages Python also provides some inbuilt data types this includes list, tuple, sets, dictionaries, etc. In this article, we will discuss the similarities and differences between lists and arrays.

The list data type is exclusively used in Python. You can use this to store multiple values in a single variable. This data type is very similar to array in c/ c++ but instead of holding a single type, simultaneously it can hold multiple different types of value such as number, string, float, etc.

An array is a collection of elements of the same type. It stores multiple values of the same type in a single variable. Python does not have built-in support for array instead you can use Python lists.

Creating list and array in Python

You can create a Python list by placing comma-separated elements inside the square brackets.

For example –

x = [5, 2, 3, "Hi", 0]

There are two ways to create arrays in Python first is by importing the array module and the second one is by importing numpy module. Numpy array supports different data types.

The example of both types of array is given below –

import array as arr
x = arr.array('i', 1, 5, 9,4, 6)
print(x)
print(type(x))

Where i is a type specifier which defines the type of array elements i is used to specify integer type of values.

import numpy as np
x = np.array(["numbers", 8, 6, 7, 0])
print(x)
print(type(x))

Similarities between Python list and array

Both list and arrays in Python has the following similarities –

  • Both data types in python are used to store multiple values in a single variable
  • Both Python list and array are mutable which means you can add or remove elements whenever you want
  • List and array in Python allow indexing, you can access elements using index
  • Both of them supports slicing

Difference between list and array

Both list and array in Python has the following difference –

  • Python list can have elements of different data type while array (except numpy array) is only consist of same type of elements
  • Lists have inbuilt python support so you need not to import any module but to use Python array you need to explicitly import array or numpy module
  • Lists are preferred for shorter sequence while array are generally preferred for longer sequence
  • Python lists consume comparatively more memory for simple operation while arrays are compact in memory size
  • Python array are more efficient (functionality and speed) than list while list are more flexible than array

Conclusion

Now you know how python array is different from list. If you want to say something on this then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.