How to define array python

How to declare an array in Python

In this article, you will learn about arrays and how to declare arrays in Python. You will see some simple code examples to understand how you can create an array in Python.

In Python, array declaration cannot be done directly, because Python doesn’t have any support for Array type bt default.

Note: Array does not exist as a built-in data structure in Python. Python uses list type instead of the array.

What is Array?

  • An array is like a storage container where multiple items of the same type are stored.
  • Like other data structures, arrays can also be accessed using indexes.
  • Elements stored in an array have a location as a numerical index.
  • The Index starts from 0 and ends with the length of the array-1.
  • Arrays use contiguous memory locations to store data.
  • Arrays look similar to the Python Lists but have different properties and different declarations.
Читайте также:  Rangeerror maximum call stack size exceeded python

Let us look at the different ways to declare arrays in Python. We will use simple approaches, an array module supported by Python, NumPy module, use a list to create an array, and also a direct method to initialize an array.

1. Declare Array in Python using List

As mentioned earlier, there is no built-in support for arrays in Python, but we can use Python lists to create array-like structures,

array1 = [0, 0, 0, 1, 2] array2 = ["cap", "bat", "rat"]

1.1. Example: Creating array just like Python list

Here, we declare an empty array. Python for loop and range() function is used to initialize an array with default values.

  • You might get confused between lists and arrays but lists are nothing but dynamic arrays.
  • Also, arrays store similar types of data whereas in lists you can store different types of data.

The below code example has an empty array. It is initialized with 5 elements carrying a default value (0).

arr = [] arr = [0 for i in range(5)] print(arr)

2. Declare an Array using the array module

Array does not exist as a built-in data structure in Python. However, Python provides a array module to declare a set of data that acts as as an array.

Here is the syntax for using it:

arrayName = array(typecode, [Initializers])

2.1. Parameters taken by array() method:

In the above syntax, typecode is used to set the codes that are used to define the type of value the array will hold.

Use array module in Python

As you can see in the table above, you can use the type code ‘i’ for using integer type values in the array, or ‘f’ for float type values, etc.

Initializers — a set of values of similar types, like, [1, 2, 3] or [«abc», «pqr», «xyz»], etc.

2.2. Creating Array using array Module

The below code example imports the Python array module and uses it to create an array in Python.

It declares an array of a set of signed integers and then prints the elements.

from array import * array1 = array('i', [10,20,30,40,50]) for x in array1: print(x)

Next, lets see how we can use the Numpy package to create and declare array in Python.

3. Python NumPy module to create an array

Python has a module numpy that can be used to declare an array.

It creates arrays and manipulates the data in them efficiently.

The numpy.empty() function is used to create an array. Let’s see a code example,

import numpy as np arr = np.empty(10, dtype=object) print(arr)
[None None None None None None None None None None]

4. Create an Array using an initializer

This method creates an array with the default values along with the specified size inside the initializer.

See the code example below:

arr_num = [0] * 2 print(arr_num) arr_str = ['P'] * 5 print(arr_str)

FAQs

Here are some frequently asked questions related to Python array declaration.

Q. Are arrays supported in Python?

Arrays are not supported in Python by default. But we can create array-like structures using Python lists.

Q. How do you declare and initialize an array in Python?

There are many different ways in which you can declare and initialize an array in Python. For example, you can use a for loop and create a list of items that can act as an array for you. Here is the code example,

# empty array arr = [] # array with some values arr = [0 for i in range(5)] print(arr)

Q. How do you initialize an array size in Python?

Because arrays are not supported in Python by default, so there is no direct way to initialize an array size in Python. But you can create a simple array using a Python list and add some values to it to initialize the array size.

arr1 = [0, 0, 0, 1, 2] arr2 = ["cap", "bat", "rat"]

In the code example above, both arr1 and arr2 have size 3.

Q. How to fill array in Python?

There are many ways to create an array in Python and fill an array with values in Python. You can use the literal style using a Python list, or use a for loop to set values, of use the array module in Python to create an array and fill values in the array in Python.

Here are some code examples,

# fill values using for loop arr1 = [0 for i in range(5)] # fill values using literal style arr2 = [1, 2, 3, 4, 5] # using initializer arr3 = [0] * 2 

Go on try these and you will see that all the variables have values filled in them.

Источник

Python Array Declaration: A Comprehensive Guide for Beginners

Python Array Declaration

In this article, we discuss different methods for declaring an array in Python, including using the Python Array Module, Python List as an Array, and Python NumPy Array. We also provide examples and syntax for each method, as well as a brief overview of built-in methods for working with arrays in Python. Let’s get started!

What is a Python Array?

As we all know, Python offers various data structures to manipulate and deal with the data values.

When it comes to ARRAY as a data structure, Python does not offer a direct way to create or work with arrays. Rather, it provides us with the below variants of Array:

  • Python Array Module: The Array module contains various methods to create and work with the values.
  • Python List: List can be considered as a dynamic array. Moreover, heterogeneous elements can be stored in Lists, unlike Arrays.
  • Python NumPy Array: NumPy arrays are best suitable for mathematical operations to be performed on a huge amount of data.

Having understood Python Arrays, let us now understand the ways through which we can declare an array in Python.

Python Array Declaration: Different Variants

The Python Array Module provides an array data structure that can store elements of the same type, such as integers or characters. It is more efficient than lists when it comes to memory usage, especially for large datasets. In this method, we use the array() function from the array module to create an array in Python.

In Python, you can declare arrays using the Python Array Module, Python List as an Array, or Python NumPy Array. The Python Array Module and NumPy Array offer more efficient memory usage and specific data types, while Python lists provide flexibility with dynamic sizing and heterogeneous elements. Built-in methods are available to manipulate and manage data within these arrays.

Array Declaration Using Python Array Module

Python Array module contains array() function , using which we can create an array in the python environment.

array.array('format code',[data])
  • format_code : It represents the type of elements to be accepted by an array. The code ‘i’ represents numeric values, while ‘f’ represents floating-point numbers.
import array arr = array.array('i', [10,20,30,40,50]) print(arr)

We’ve imported the array module and created an array arr using the array() function with the format code ‘i’ (indicating that the array should store signed integers). We then passed a list of integers `[10, 20, 30, 40, 50]` as the data for the array. At the end, we printed the array, to show it with the specified format code and elements.

Array Declaration Using Python List as an Array

Python lists are versatile and can be used as a more flexible alternative to arrays. Lists store elements of different data types, change their size dynamically, and offer a variety of built-in methods for manipulating the data. In this method, we use the Python list to store and manage elements like an array.

lst = [10,20,30,40, 'Python'] print(lst)

In this example, we’re working with Python lists as an array. Here, we’ve created a variable named lst which contains both integers and a string named “Python”. Because lists do not care about the data that you enter in them, list arrays are quite flexible compared to the Python array module.

Array Declaration Using Python NumPy Array

The NumPy module contains various functions to create and work with array as a data structure. The numpy.array() function can be used to create single as well as multi-dimensional array in Python. It creates an array object as ‘ndarray’.

Example: Array creation using numpy.array() function

import numpy arr = numpy.array([10,20]) print(arr)

Further, we can use numpy.arange() function to create an array within the specific range of data values.

  • start : The starting element of the array.
  • end : The last element of the array.
  • step : The number of interval or steps between array elements.
import numpy arr = numpy.arange(1,10,2) print(arr)

Methods of An Array

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

Method Description
append() Add an element at the end of the list
clear() Remove all the elements from the list
copy() Return a copy of the list
count() Return 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() Return the index of the first element with the specified value
insert() Add an element at the specified position
pop() Remove the element at the specified position
remove() Remove the first item with the specified value
reverse() Reverse the order of the list
sort() Sort the list

Summary

In this article, we’ve covered various methods to declare and work with arrays in Python, such as the Python Array Module, Python List as an Array, and Python NumPy Array. We also discussed built-in methods that can be used on lists and arrays. Understanding these concepts will help you effectively manage and manipulate data in your Python projects. If you have any questions or suggestions, feel free to leave a comment below.

References

Источник

Оцените статью