What is the difference between Python Arrays and lists?

Hi, What is the difference between Python Arrays and lists?

3 Likes

Normally one would think they are the same in Python, but they are not.

The major difference between the two is that List doesnā€™t need to be declared explicitly whereas Arrays does.

# this is a list
list = [3, 6, 9, 12]

# this is an array
# 'i' signifies that all elements in array are integers
array_nums = arr.array("i", [3, 6, 9, 12])

Also, in List, you can have different types of values in the same list. For example: [1, ā€œStringā€, ā€˜cā€™]

But in Arrays, you need to have homogenous values. For example: [1, 2, 3], or [ā€œString1ā€, ā€œString2ā€], etc. If you try to add a heterogenous value inside an array in Python, you will get an error.

1 Like