How to Create an Array in Python

Techwalla may earn compensation through affiliate links in this story.

How to Create an Array in Python. Arrays are useful and fundamental structures that exist in every high-level language. In Python, arrays are native objects called "lists," and they have a variety of methods associated with each object.

Step 1

Create a List With Text or Numeric Elements. You can create a list with a series of text elements in one line in Python.

List out the text elements you want, separated by commas:my_array = ['rebecca', 'juan', 'samir', 'heather']You may also use numbers in the array:my_array = [-1,0,1,2]Or you can mix and match letters and numbers:my_array = [1, 'rebecca', 'allard', 15]

Step 2

Access the values of an array by using an index.

Know that this index is 0 based, meaning that the first element of the array is referenced by using position 0, the second element of the list is referenced by using position 1, and so forth:print my_array[2]>>>> samir

Step 3

Use a list as a dictionary. You can use a dictionary to look up name value pairs for quick retrieval.

Use a dictionary to look up last names associated with a first name. For example:my_dic['rebecca'] = 'allard'my_dic['juan'] = 'hernandez'my_dic['heather'] = 'aston'You can then use the dictionary to print out the value (the last name) using the key (the first name):print my_dic['rebecca'] >>>> allard

Step 4

Nest a list--realize that arrays in Python can contain any data type, including other arrays.

Create a list that contains another by simply inserting it into the array element list. For example:my_friends = ['rebecca', 'ben', 'biella', 'kevin']my_contacts = ['steve', my_friends, 'lee']You can now use my_contacts as a normal array:print my_contacts[0]>>>> steveAnd you can access the nested list by using a second reference:print my_contacts[1][2]>>>> biella