---
title: Python Arrays
description: "> ## Python Arrays – Python Массивууд *Arguments* are often shortened to *args* in Python documentations. *Аргументууд* нь ихэвчлэн Python-д *`args`* гэж товчилсон байдаг. ### Arrays – Массивууд **Note:** This page shows you how to use LISTS as ARRAYS, however, to work with arrays in…"
url: "https://apprentice.mn/docs/python-arrays/"
updated: "2024-07-30"
category: Python
---

# Python Arrays

> ## Python Arrays – Python Массивууд

*Arguments* are often shortened to *args* in Python documentations.

*Аргументууд* нь ихэвчлэн Python-д *`args`* гэж товчилсон байдаг.

### Arrays – Массивууд

**Note:** This page shows you how to use LISTS as ARRAYS, however, to work with arrays in Python you will have to import a library, like the NumPy library.

**Тайлбар:** Энэ хуудас танд жагсаалтыг хэрхэн ашиглах талаар зааж өгч байгаа боловч Python дээр массивтай ажиллахын тулд NumPy номын сан гэх мэт номын санг импортлох шаардлагатай.

Arrays are used to store multiple values in one single variable:

Массив нь нэг хувьсагчид олон утгыг хадгалахад ашиглагддаг.

##### Example – Жишээ

Create an array containing car names:

Автомашины нэрс агуулсан массив үүсгэх:

`cars = ["Ford", "Volvo", "BMW"]`

### What is an Array? – Массив гэж юу вэ?

An array is a special variable, which can hold more than one value at a time.

Массив нь нэг дор олон утгыг хадгалж чадах тусгай хувьсагч юм.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

Жишээ нь, танд автомашины нэрсийн жагсаалт байгаа гэж бодъё. Эдгээр машиныг тус тусдаа хувьсагчид хадгалах нь төвөгтэй байж болно:

car1 = “Ford”
car2 = “Volvo”
car3 = “BMW”

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

Гэхдээ хэрэв танд 3 биш 300 машин байсан бол яах вэ? 

The solution is an array!

Энэ үед массив нь маш үр дүнтэй шийдэл болно!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Массив нь олон утгыг нэг нэр дор хадгалж чаддаг бөгөөд индексийн дугаараар утгад хандаж болно.

### Access the Elements of an Array – Массивын элементүүдэд хандах

You refer to an array element by referring to the *index number*.

Та массивын элементийг *индексийн дугаараар* нь тодорхойлж болно.

#### Example – Жишээ

Get the value of the first array item:

Эхний массивын элементийн утгыг авах:

`x = cars[0]`

##### Example – Жишээ

Modify the value of the first array item:

Эхний массивын элементийн утгыг өөрчлөх:

`x = cars[0] = "Toyota"`

### The Length of an Array – Массивын урт

Use the `len()` method to return the length of an array (the number of elements in an array).

Массивын уртыг (массив дахь элементүүдийн тоог) тодорхойлоход `len()` аргыг ашиглана.

#### Example – Жишээ

Return the number of elements in the `cars` array:

`cars` массив дахь элементүүдийн тоог буцаах:

`x = len(cars)`

**Note:** The length of an array is always one more than the highest array index.

**Тэмдэглэл:** Массивын урт нь үргэлж индексээс нэгээр илүү байдаг.

### Looping Array Elements – Массивын элементүүдийг давталтаар гүйцэтгэх

You can use the `for in` loop to loop through all the elements of an array.

Та `for in` давталтыг ашиглан массив дахь бүх элементүүдийг давтаж болно.

#### Example – Жишээ

Print each item in the `cars` array:

`cars` массив дахь элемент тус бүрийг хэвлэх:

`for x in cars:  print(x)`

### Adding Array Elements – Массивын элементүүдийг нэмэх

You can use the `append()` method to add an element to an array.

Массивд элемент нэмэхийн тулд `append()` аргыг ашиглаж болно.

#### Example – Жишээ

Add one more element to the `cars` array:

`cars` массивд нэг элемент нэмэх:

`cars.append("Honda")`

### Removing Array Elements – Массивын элементүүдийг устгах

You can use the `pop()` method to remove an element from the array.

Массивын элемент устгахад `pop()` аргыг ашиглаж болно.

#### Example – Жишээ

Delete the second element of the `cars` array:

`cars` массивын хоёр дахь элементийг устгах:

`cars.pop(1)`

You can also use the `remove()` method to remove an element from the array.

Мөн `remove()` аргыг ашиглан тодорхой утгатай элементийг устгаж болно.

##### Example – Жишээ

Delete the element that has the value “Volvo”:

“Volvo” утгатай элементийг устгах:

`cars.remove("Volvo")`

**Note:** The list’s `remove()` method only removes the first occurrence of the specified value.

**Тайлбар:** Жагсаалтын `remove()` арга нь зөвхөн тодорхойлсон утгын анхны тохиолдыг устгадаг.

### Array Methods – Массивын аргууд

Python has a set of built-in methods that you can use on lists/arrays.

Python нь жагсаалт/массив дээр ашиглаж болох олон төрлийн суурь аргуудтай.

| Method Арга | Description Тайлбар |
| --- | --- |
| append() | Adds an element at the end of the list Жагсаалтын төгсгөлд элемент нэмнэ |
| clear() | Removes all the elements from the list Жагсаалтын бүх элементүүдийг устгана |
| copy() | Returns a copy of the list Жагсаалтын хуулбарыг буцаана |
| count() | Returns the number of elements with the specified value Тодорхой утгатай элементүүдийн тоог буцаана |
| extend() | Add the elements of a list (or any iterable), to the end of the current list Жагсаалтын төгсгөлд өөр жагсаалтын элементүүдийг нэмнэ |
| index() | Returns the index of the first element with the specified value Тодорхой утгатай эхний элементийн индексийг буцаана |
| insert() | Adds an element at the specified position Тодорхой байрлалд элемент нэмнэ |
| pop() | Removes the element at the specified position Тодорхой байрлалд байгаа элементийг устгана |
| remove() | Removes the first item with the specified value Тодорхой утгатай анхны элементийг устгана |
| reverse() | Reverses the order of the list Жагсаалтын элементийн дарааллыг урвуулна |
| sort() | Sorts the list Жагсаалтыг эрэмбэлнэ |

**Note:** Python does not have built-in support for Arrays, but Python Lists can be used instead.

**Тайлбар:** Python-д массивуудын хувьд суурь дэмжлэг байхгүй, харин жагсаалтуудыг массив болгон ашиглаж болно.

> ## Methods

### Python List append() Method

##### Example

Add an element to the `fruits` list:

`fruits = ['apple', 'banana', 'cherry']fruits.append("orange")`

#### Definition and Usage

The `append()` method appends an element to the end of the list.

---

#### Syntax

*list*.append(*elmnt*)

#### Parameter Values

| Parameter | Description |
| --- | --- |
| *elmnt* | Required. An element of any type (string, number, object etc.) |

#### More Examples

##### Example

Add a list to a list:

`a = ["apple", "banana", "cherry"]b = ["Ford", "BMW", "Volvo"]a.append(b)`

### Python List clear() Method

##### Example

Remove all elements from the `fruits` list:

`fruits = ['apple', 'banana', 'cherry', 'orange']fruits.clear()`

#### Definition and Usage

The `clear()` method removes all the elements from a list.

---

#### Syntax

*list*.clear()

#### Parameter Values

No parameters

### Python List copy() Method

##### Example

Copy the `fruits` list:

`fruits = ['apple', 'banana', 'cherry', 'orange']x = fruits.copy()`

#### Definition and Usage

The `copy()` method returns a copy of the specified list.

---

#### Syntax

*list*.copy()

#### Parameter Values

No parameters

### Python List count() Method

##### Example

Return the number of times the value “cherry” appears in the `fruits` list:

`fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")`

#### Definition and Usage

The `count()` method returns the number of elements with the specified value.

---

#### Syntax

*list*.count(*value*)

#### Parameter Values

| Parameter | Description |
| --- | --- |
| *value* | Required. Any type (string, number, list, tuple, etc.). The value to search for. |

#### More Examples

##### Example

Return the number of times the value 9 appears int the list:

`points = [1, 4, 2, 9, 7, 8, 9, 3, 1]x = points.count(9)`

### Python List extend() Method

##### Example

Add the elements of `cars` to the `fruits` list:

`fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)`

#### Definition and Usage

The `extend()` method adds the specified list elements (or any iterable) to the end of the current list.

---

#### Syntax

*list*.extend(*iterable*)

#### Parameter Values

| Parameter | Description |
| --- | --- |
| *iterable* | Required. Any iterable (list, set, tuple, etc.) |

#### More Examples

##### Example

Add a tuple to the `fruits` list:

`fruits = ['apple', 'banana', 'cherry']
points = (1, 4, 5, 9)
fruits.extend(points)`

### Python List index() Method

##### Example

What is the position of the value “cherry”:

`fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")`

#### Definition and Usage

The `index()` method returns the position at the first occurrence of the specified value.

---

#### Syntax

*list*.index(*elmnt*)

#### Parameter Values

| Parameter | Description |
| --- | --- |
| *elmnt* | Required. Any type (string, number, list, etc.). The element to search for |

#### More Examples

##### Example

What is the position of the value 32:

`fruits = [4, 55, 64, 32, 16, 32]
x = fruits.index(32)`

**Note:** The `index()` method only returns the *first* occurrence of the value.

### Python List insert() Method

##### Example

Insert the value “orange” as the second element of the `fruit` list:

`fruits = ['apple', 'banana', 'cherry']fruits.insert(1, "orange")`

#### Definition and Usage

The `insert()` method inserts the specified value at the specified position.

---

#### Syntax

*list*.insert(*pos*, *elmnt*)

#### Parameter Values

| Parameter | Description |
| --- | --- |
| *pos* | Required. A number specifying in which position to insert the value |
| *elmnt* | Required. An element of any type (string, number, object etc.) |

### Python List pop() Method

##### Example

Remove the second element of the `fruit `list:

`fruits = ['apple', 'banana', 'cherry']fruits.pop(1)`

#### Definition and Usage

The `pop()` method removes the element at the specified position.

---

#### Syntax

*list*.pop(*pos*)

#### Parameter Values

| Parameter | Description |
| --- | --- |
| *pos* | Optional. A number specifying the position of the element you want to remove, default value is -1, which returns the last item |

#### More Examples

##### Example

Return the removed element:

`fruits = ['apple', 'banana', 'cherry']
x = fruits.pop(1)`

**Note:** The `pop()` method returns removed value.

### Python List remove() Method

##### Example

Remove the “banana” element of the `fruit `list:

`fruits = ['apple', 'banana', 'cherry']fruits.remove("banana")`

#### Definition and Usage

The `remove()` method removes the first occurrence of the element with the specified value.

---

#### Syntax

*list*.remove(*elmnt*)

#### Parameter Values

| Parameter | Description |
| --- | --- |
| *elmnt* | Required. Any type (string, number, list etc.) The element you want to remove |

### Python List reverse() Method

##### Example

Reverse the order of the `fruit `list:

`fruits = ['apple', 'banana', 'cherry']fruits.reverse()`

#### Definition and Usage

The `reverse()` method reverses the sorting order of the elements.

---

#### Syntax

*list*.reverse()

#### Parameter Values

No parameters

### Python List sort() Method

##### Example

Sort the list alphabetically:

`cars = ['Ford', 'BMW', 'Volvo']
cars.sort()`

#### Definition and Usage

The `sort()` method sorts the list ascending by default.

You can also make a function to decide the sorting criteria(s).

---

#### Syntax

*list*.sort(reverse=True|False, key=myFunc)

#### Parameter Values

| Parameter | Description |
| --- | --- |
| reverse | Optional. reverse=True will sort the list descending. Default is reverse=False |
| key | Optional. A function to specify the sorting criteria(s) |

#### More Examples

##### Example

Sort the list descending:

`cars = ['Ford', 'BMW', 'Volvo']cars.sort(reverse=True)`

##### Example

Sort the list by the length of the values:

`# A function that returns the length of the value:def myFunc(e):  return len(e)cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']cars.sort(key=myFunc)`

##### Example

Sort a list of dictionaries based on the “year” value of the dictionaries:

`# A function that returns the 'year' value:
def myFunc(e):  return e['year']
cars = [  {'car': 'Ford', 'year': 2005},  {'car': 'Mitsubishi', 'year': 2000},  {'car': 'BMW', 'year': 2019},  {'car': 'VW', 'year': 2011}
]
cars.sort(key=myFunc)`

##### Example

Sort the list by the length of the values *and* reversed:

`# A function that returns the length of the value:def myFunc(e):  return len(e)cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']cars.sort(reverse=True, key=myFunc)`

               [https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-arrays%2F&linkname=Python%C2%A0Arrays](https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-arrays%2F&linkname=Python%C2%A0Arrays)[https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-arrays%2F&linkname=Python%C2%A0Arrays](https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-arrays%2F&linkname=Python%C2%A0Arrays)[https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-arrays%2F&linkname=Python%C2%A0Arrays](https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-arrays%2F&linkname=Python%C2%A0Arrays)[https://www.addtoany.com/share](https://www.addtoany.com/share)
