Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
1.8k views
in Blog Post by 48 54 93
edited by

In this post, we're gonna learn about arrays in Python.

Python arrays


What is an Array?

Below, a list of the most usable definitions of an array:

  • An array is a container that holds data (an ordered collection of items)
  • An array is a data structure that stores values of the same data type.
  • Arrays are used to store multiple values in one single variable instead of declaring separate variables for each value.

How can we access the array elements?

  • Each element in an array has an index and it is accessed by this index.
  • The index starts with zero and goes up one at a time and there are some programming languages like Cobol which start with index 1.

The major operations in data structure are (Access, Insert, Delete, Find, Sort) an element  


Arrays in Python

  • Python does not have built-in support for Arrays.
  • Python lists can be used instead of arrays.
  • The main difference between arrays and lists is that we cannot constrain the type of elements stored in a list example a=[1,2.4,”hello”].
  • To use arrays in python language, you need to import the standard ‘array’ module
    • from array import *

Array declaration in Python

arrayIdentifierName = array(typecode, [Initializers]

 Typecodes are the codes that are used to define the type of array values.

  • ‘b’     is for  signed integer of size 1 byte
  • ‘B’     is for  unsigned integer of size 1 byte
  • ‘c’      is for  character of size 1 byte
  • ‘u’      is for  Unicode character of size 2 bytes
  • ‘h’      is for  signed integer of size 2 bytes
  • ‘H’     is for  unsigned integer of size 2 bytes
  • ‘i’       is for  signed integer of size 2 bytes
  • ‘I’       is for  unsigned integer of size 2 bytes
  • ‘w’     is for  Unicode character of size 4 bytes
  • ‘l’       is for  signed integer of size 4 bytes
  • ‘L’      is for unsigned integer of size 4 bytes
  • ‘f’       is for  floating point of size 4 bytes
  • ‘d’      is for  floating point of size 8 bytes

Access an array element in Python

  • We access the elements with its index that start from 0 index

access array in python


Array length in Python

  • Use the len() method to return the length of an array.


Looping array elements in Python

  • looping the array element by using for loop

looping an array elements in python


Sort arrays in Python

Using sort() you will sort the given list in ascending order.

list_name.sort()

You can set reverse= true to sort in descending order

list_name.sort(reverse=True)

Sort array in python


Conclusion

In this post, we have learned about arrays in Python.

See Also


1.1k questions

673 answers

454 comments

193k users

تعلم بالعربي PowerApps

تعلم بالعربي Power Automate

If you don’t ask, the answer is always NO!
...