DEV Community šŸ‘©ā€šŸ’»šŸ‘Øā€šŸ’»

Ilya R
Ilya R

Posted on

Python3. Difference between array and list.

In Python, lists and arrays are sets of values. This values are called elements.

Usually, elements are any type of data, including even objects and other arrays and lists.

But not for array in Python. Arrays in Python are vary simmilar to lists. But they have some difference. The size and type of an element in an array is determined when it is created.

Let look how we can create an array in Python.

from array import array

numbers = array('i', [2, 4, 6, 8])
print numbers[0]
Enter fullscreen mode Exit fullscreen mode

In example, first of all, the array module is imported for work with arrays in Python.

Next, a new array is created. In this array all elements are the integer type.

First argument is a typecode. It define which type of data will be in array. For example, ā€˜iā€™ it is int type. But ā€˜uā€™ means type of elements in array will be unicode characters. For type float need mention ā€˜dā€™.

With lists in Python, work will be a little differently. Lists can contain elements of different data types.

list1 = [] #Creating of empty list
list2 = ['a', 'b', 2, ['c', 3]]
Enter fullscreen mode Exit fullscreen mode

Here we created two lists. One of them are emtpy. Second list conteains elements of different data types.

Top comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

This confused me a lot to start with coming from JavaScript but I got the hang of it.

šŸŒš Life is too short to browse without dark mode