Python - Arrays
Python - Arrays
Hint: When you’re stuck, always refer to the official Python documentation
Arrays in other languages != arrays in Python
In programming, an array is a collection of elements of the same type.
Arrays are popular in most programming languages like Java, C/C++, JavaScript
and so on.
However, in Python, they are not that common. When people talk about
Python arrays, more often than not, they are talking about Python lists.
It is important to know the difference between a list and an array so you know
the correct tools for your own software.
Why do we use array?
Reasons:
- In simple sequences that hold the same data type such as [1, 2, 3, 4, 5],
arrays will take up less memory space than lists. BECAUSE it is of the
same data type, sizeof(one object) * length bytes of memory.
Python modules are .py files that consist of Python code. Any Python file can be
referenced as a module.
Some modules are available through the Python Standard Library and are therefore
installed with your Python installation. e.g. random, array
Others, you can install elsewhere and you can even create modules for yourself!
Built-in Functions
array.append(x)
array.count(x)
array.insert(i, x)
Insert a new item with value x in the array before position i. Negative values are treated as being relative
to the end of the array.
array.pop([i])
Removes the item with the index i from the array and returns it. The optional argument defaults to -1, so
that by default the last item is removed and returned.
array.remove(x)
Remove the first occurrence of x from the array.
array.reverse()
Reverse the order of the items in the array.
array.fromlist(list)
Append items from the list. This is equivalent to for x in list: a.append(x) except that if there is
a type error, the array is unchanged.