Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python arrays.

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

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 .

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

Create an array containing car names:

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:

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?

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 .

Get the value of the first array item:

Modify the value of the first array item:

The Length of an Array

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

Return the number of elements in the cars array:

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

Advertisement

Looping Array Elements

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

Print each item in the cars array:

Adding Array Elements

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

Add one more element to the cars array:

Removing Array Elements

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

Delete the second element of the cars array:

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

Delete the element that has the value "Volvo":

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

Array Methods

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

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Python »
  • 3.12.3 Documentation »
  • The Python Standard Library »
  • Data Types »
  • array — Efficient arrays of numeric values
  • Theme Auto Light Dark |

array — Efficient arrays of numeric values ¶

This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code , which is a single character. The following type codes are defined:

It can be 16 bits or 32 bits depending on the platform.

Changed in version 3.9: array('u') now uses wchar_t as C type instead of deprecated Py_UNICODE . This change doesn’t affect its behavior because Py_UNICODE is alias of wchar_t since Python 3.3.

Deprecated since version 3.3, will be removed in version 4.0.

The actual representation of values is determined by the machine architecture (strictly speaking, by the C implementation). The actual size can be accessed through the array.itemsize attribute.

The module defines the following item:

A string with all available type codes.

The module defines the following type:

A new array whose items are restricted by typecode , and initialized from the optional initializer value, which must be a bytes or bytearray object, a Unicode string, or iterable over elements of the appropriate type.

If given a bytes or bytearray object, the initializer is passed to the new array’s frombytes() method; if given a Unicode string, the initializer is passed to the fromunicode() method; otherwise, the initializer’s iterator is passed to the extend() method to add initial items to the array.

Array objects support the ordinary sequence operations of indexing, slicing, concatenation, and multiplication. When using slice assignment, the assigned value must be an array object with the same type code; in all other cases, TypeError is raised. Array objects also implement the buffer interface, and may be used wherever bytes-like objects are supported.

Raises an auditing event array.__new__ with arguments typecode , initializer .

The typecode character used to create the array.

The length in bytes of one array item in the internal representation.

Append a new item with value x to the end of the array.

Return a tuple (address, length) giving the current memory address and the length in elements of the buffer used to hold array’s contents. The size of the memory buffer in bytes can be computed as array.buffer_info()[1] * array.itemsize . This is occasionally useful when working with low-level (and inherently unsafe) I/O interfaces that require memory addresses, such as certain ioctl() operations. The returned numbers are valid as long as the array exists and no length-changing operations are applied to it.

When using array objects from code written in C or C++ (the only way to effectively make use of this information), it makes more sense to use the buffer interface supported by array objects. This method is maintained for backward compatibility and should be avoided in new code. The buffer interface is documented in Buffer Protocol .

“Byteswap” all items of the array. This is only supported for values which are 1, 2, 4, or 8 bytes in size; for other types of values, RuntimeError is raised. It is useful when reading data from a file written on a machine with a different byte order.

Return the number of occurrences of x in the array.

Append items from iterable to the end of the array. If iterable is another array, it must have exactly the same type code; if not, TypeError will be raised. If iterable is not an array, it must be iterable and its elements must be the right type to be appended to the array.

Appends items from the bytes-like object , interpreting its content as an array of machine values (as if it had been read from a file using the fromfile() method).

Added in version 3.2: fromstring() is renamed to frombytes() for clarity.

Read n items (as machine values) from the file object f and append them to the end of the array. If less than n items are available, EOFError is raised, but the items that were available are still inserted into the array.

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.

Extends this array with data from the given Unicode string. The array must have type code 'u' ; otherwise a ValueError is raised. Use array.frombytes(unicodestring.encode(enc)) to append Unicode data to an array of some other type.

Return the smallest i such that i is the index of the first occurrence of x in the array. The optional arguments start and stop can be specified to search for x within a subsection of the array. Raise ValueError if x is not found.

Changed in version 3.10: Added optional start and stop parameters.

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.

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.

Remove the first occurrence of x from the array.

Reverse the order of the items in the array.

Convert the array to an array of machine values and return the bytes representation (the same sequence of bytes that would be written to a file by the tofile() method.)

Added in version 3.2: tostring() is renamed to tobytes() for clarity.

Write all items (as machine values) to the file object f .

Convert the array to an ordinary list with the same items.

Convert the array to a Unicode string. The array must have a type 'u' ; otherwise a ValueError is raised. Use array.tobytes().decode(enc) to obtain a Unicode string from an array of some other type.

The string representation of array objects has the form array(typecode, initializer) . The initializer is omitted if the array is empty, otherwise it is a Unicode string if the typecode is 'u' , otherwise it is a list of numbers. The string representation is guaranteed to be able to be converted back to an array with the same type and value using eval() , so long as the array class has been imported using from array import array . Variables inf and nan must also be defined if it contains corresponding floating point values. Examples:

Packing and unpacking of heterogeneous binary data.

Packing and unpacking of External Data Representation (XDR) data as used in some remote procedure call systems.

The NumPy package defines another array type.

Previous topic

bisect — Array bisection algorithm

weakref — Weak references

  • Report a Bug
  • Show Source

Nick McCullum Headshot

Nick McCullum

Software Developer & Professional Explainer

NumPy Indexing and Assignment

Hey - Nick here! This page is a free excerpt from my $199 course Python for Finance, which is 50% off for the next 50 students.

If you want the full course, click here to sign up.

In this lesson, we will explore indexing and assignment in NumPy arrays.

The Array I'll Be Using In This Lesson

As before, I will be using a specific array through this lesson. This time it will be generated using the np.random.rand method. Here's how I generated the array:

Here is the actual array:

To make this array easier to look at, I will round every element of the array to 2 decimal places using NumPy's round method:

Here's the new array:

How To Return A Specific Element From A NumPy Array

We can select (and return) a specific element from a NumPy array in the same way that we could using a normal Python list: using square brackets.

An example is below:

We can also reference multiple elements of a NumPy array using the colon operator. For example, the index [2:] selects every element from index 2 onwards. The index [:3] selects every element up to and excluding index 3. The index [2:4] returns every element from index 2 to index 4, excluding index 4. The higher endpoint is always excluded.

A few example of indexing using the colon operator are below.

Element Assignment in NumPy Arrays

We can assign new values to an element of a NumPy array using the = operator, just like regular python lists. A few examples are below (note that this is all one code block, which means that the element assignments are carried forward from step to step).

arr[2:5] = 0.5

Returns array([0. , 0. , 0.5, 0.5, 0.5])

As you can see, modifying second_new_array also changed the value of new_array .

Why is this?

By default, NumPy does not create a copy of an array when you reference the original array variable using the = assignment operator. Instead, it simply points the new variable to the old variable, which allows the second variable to make modification to the original variable - even if this is not your intention.

This may seem bizarre, but it does have a logical explanation. The purpose of array referencing is to conserve computing power. When working with large data sets, you would quickly run out of RAM if you created a new array every time you wanted to work with a slice of the array.

Fortunately, there is a workaround to array referencing. You can use the copy method to explicitly copy a NumPy array.

An example of this is below.

As you can see below, making modifications to the copied array does not alter the original.

So far in the lesson, we have only explored how to reference one-dimensional NumPy arrays. We will now explore the indexing of two-dimensional arrays.

Indexing Two-Dimensional NumPy Arrays

To start, let's create a two-dimensional NumPy array named mat :

There are two ways to index a two-dimensional NumPy array:

  • mat[row, col]
  • mat[row][col]

I personally prefer to index using the mat[row][col] nomenclature because it is easier to visualize in a step-by-step fashion. For example:

You can also generate sub-matrices from a two-dimensional NumPy array using this notation:

Array referencing also applies to two-dimensional arrays in NumPy, so be sure to use the copy method if you want to avoid inadvertently modifying an original array after saving a slice of it into a new variable name.

Conditional Selection Using NumPy Arrays

NumPy arrays support a feature called conditional selection , which allows you to generate a new array of boolean values that state whether each element within the array satisfies a particular if statement.

An example of this is below (I also re-created our original arr variable since its been awhile since we've seen it):

You can also generate a new array of values that satisfy this condition by passing the condition into the square brackets (just like we do for indexing).

An example of this is below:

Conditional selection can become significantly more complex than this. We will explore more examples in this section's associated practice problems.

In this lesson, we explored NumPy array indexing and assignment in thorough detail. We will solidify your knowledge of these concepts further by working through a batch of practice problems in the next section.

Guide to Arrays in Python

array assignment python

An array is a structured way to store multiple items (like numbers, characters, or even other arrays) in a specific order, and you can quickly access, modify, or remove any item if you know its position (index).

In this guide, we'll give you a comprehensive overview of the array data structure. First of all, we'll take a look at what arrays are and what are their main characteristics. We'll then transition into the world of Python, exploring how arrays are implemented, manipulated, and applied in real-world scenarios.
  • Understanding the Array Data Structure

Arrays are among the oldest and most fundamental data structures used in computer science and programming. Their simplicity, combined with their efficiency in certain operations, makes them a staple topic for anyone delving into the realm of data management and manipulation.

An array is a collection of items, typically of the same type , stored in contiguous memory locations .

This contiguous storage allows arrays to provide constant-time access to any element, given its index. Each item in an array is called an element , and the position of an element in the array is defined by its index , which usually starts from zero .

For instance, consider an array of integers: [10, 20, 30, 40, 50] . Here, the element 20 has an index of 1 :

python array indexing

There are multiple advantages of using arrays to store our data. For example, due to their memory layout, arrays allow for O(1) (constant) time complexity when accessing an element by its index. This is particularly beneficial when we need random access to elements. Additionally, arrays are stored in contiguous memory locations , which can lead to better cache locality and overall performance improvements in certain operations. Another notable advantage of using arrays is that, since arrays have a fixed size once declared, it's easier to manage memory and avoid unexpected overflows or out-of-memory errors.

Note : Arrays are especially useful in scenarios where the size of the collection is known in advance and remains constant , or where random access is more frequent than insertions and deletions.

On the other side, arrays come with their own set of limitations . One of the primary limitations of traditional arrays is their fixed size . Once an array is created, its size cannot be changed. This can lead to issues like wasted memory (if the array is too large) or the need for resizing (if the array is too small). Besides that, inserting or deleting an element in the middle of an array requires shifting of elements, leading to O(n) time complexity for these operations.

To sum this all up, let's illustrate the main characteristics of arrays using the song playlist example from the beginning of this guide. An array is a data structure that:

Is Indexed: Just like each song on your playlist has a number (1, 2, 3, ...), each element in an array has an index. But, in most programming languages, the index starts at 0. So, the first item is at index 0, the second at index 1, and so on.

Has Fixed Size : When you create a playlist for, say, 10 songs, you can't add an 11th song without removing one first. Similarly, arrays have a fixed size. Once you create an array of a certain size, you can't add more items than its capacity.

Is Homogeneous : All songs in your playlist are music tracks. Similarly, all elements in an array are of the same type. If you have an array of integers, you can't suddenly store a text string in it.

Has Direct Access : If you want to listen to the 7th song in your playlist, you can jump directly to it. Similarly, with arrays, you can instantly access any element if you know its index.

Contiguous Memory : This is a bit more technical. When an array is created in a computer's memory, it occupies a continuous block of memory. Think of it like a row of adjacent lockers in school. Each locker is next to the other, with no gaps in between.

  • Python and Arrays

Python, known for its flexibility and ease of use, offers multiple ways to work with arrays. While Python does not have a native array data structure like some other languages, it provides powerful alternatives that can function similarly and even offer extended capabilities.

At first glance, Python's list might seem synonymous with an array, but there are subtle differences and nuances to consider:

Looking at this table, it comes naturally to ask - "When to use which?" . Well, if you need a collection that can grow or shrink dynamically and can hold mixed data types, Python's list is the way to go. However, for scenarios requiring a more memory-efficient collection with elements of the same type, you might consider using Python's array module or external libraries like NumPy.

  • The array Module in Python

When most developers think of arrays in Python, they often default to thinking about lists. However, Python offers a more specialized array structure through its built-in array module. This module provides a space-efficient storage of basic C-style data types in Python.

While Python lists are incredibly versatile and can store any type of object, they can sometimes be overkill, especially when you only need to store a collection of basic data types, like integers or floats. The array module provides a way to create arrays that are more memory efficient than lists for specific data types.

  • Creating an Array

To use the array module, you first need to import it:

Once imported, you can create an array using the array() constructor:

Here, the 'i' argument indicates that the array will store signed integers . There are several other type codes available, such as 'f' for floats and 'd' for doubles.

  • Accessing and Modifying Elements

You can access and modify elements in an array just like you would with a list:

And now, let's modify the element by changing it's value to 6 :

  • Array Methods

The array module provides several methods to manipulate arrays:

append() - Adds an element to the end of the array:

extend() - Appends iterable elements to the end:

pop() - Removes and returns the element at the given position:

remove() : Removes the first occurrence of the specified value:

reverse() : Reverses the order of the array:

Note: There are more methods than we listed here. Refer to the official Python documentation to see a list of all available methods in the array module.

While the array module offers a more memory-efficient way to store basic data types, it's essential to remember its limitations . Unlike lists, arrays are homogeneous . This means all elements in the array must be of the same type. Also, you can only store basic C-style data types in arrays. If you need to store custom objects or other Python types, you'll need to use a list or another data structure.

  • NumPy Arrays

NumPy, short for Numerical Python, is a foundational package for numerical computations in Python. One of its primary features is its powerful N-dimensional array object , which offers fast operations on arrays, including mathematical, logical, shape manipulation, and more.

NumPy arrays are more versatile than Python's built-in array module and are a staple in data science and machine learning projects.
  • Why Use NumPy Arrays?

The first thing that comes to mind is performance . NumPy arrays are implemented in C and allow for efficient memory storage and faster operations due to optimized algorithms and the benefits of contiguous memory storage.

While Python's built-in arrays are one-dimensional, NumPy arrays can be multi-dimensional , making them ideal for representing matrices or tensors.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Finally, NumPy provides a vast array of functions to operate on these arrays, from basic arithmetic to advanced mathematical operations, reshaping, splitting, and more.

Note: When you know the size of the data in advance, pre-allocating memory for arrays (especially in NumPy) can lead to performance improvements.

  • Creating a NumPy Array

To use NumPy, you first need to install it ( pip install numpy ) and then import it:

Once imported, you can create a NumPy array using the array() function:

You can also create multi-dimensional arrays:

This will give us:

Besides these basic ways we can create arrays, NumPy provides us with other clever ways we can create arrays. One of which is the arange() method. It creates arrays with regularly incrementing values:

Another one is the linspace() method, which creates arrays with a specified number of elements, spaced equally between specified beginning and end values:

Accessing and modifying elements in a NumPy array is intuitive:

Doing pretty much the same for multi-dimensional arrays:

Will change the value of the element in the second row (index 1 ) and the third column (index 2 ):

  • Changing the Shape of an Array

NumPy offers many functions and methods to manipulate and operate on arrays. For example, you can use the reshape() method to change the shape of an array . Say we have a simple array:

And we want to reshape it to a 3x4 matrix. All you need to do is use the reshape() method with desired dimensions passed as arguments:

This will result in:

  • Matrix Multiplication

The numpy.dot() method is used for matrix multiplication . It returns the dot product of two arrays. For one-dimensional arrays, it is the inner product of the arrays. For 2-dimensional arrays, it is equivalent to matrix multiplication , and for N-D, it is a sum product over the last axis of the first array and the second-to-last of the second array.

Let's see how it works. First, let's compute the dot product of two 1-D arrays (the inner product of the vectors):

32 is, in fact, the inner product of the two arrays - (1 4 + 2 5 + 3*6) . Next, we can perform matrix multiplication of two 2-D arrays:

Which will give us:

NumPy arrays are a significant step up from Python's built-in lists and the array module, especially for scientific and mathematical computations. Their efficiency, combined with the rich functionality provided by the NumPy library, makes them an indispensable tool for anyone looking to do numerical operations in Python.

Advice: This is just a quick overview of what you can do with the NumPy library. For more information about the library, you can read our "NumPy Tutorial: A Simple Example-Based Guide"

You might also like...

  • Guide to Hash Tables in Python
  • Dictionaries vs Arrays in Python - Deep Dive
  • Modified Preorder Tree Traversal in Django
  • Stacks and Queues in Python
  • Python Performance Optimization

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

In this article

array assignment python

Graphs in Python - Theory and Implementation

Graphs are an extremely versatile data structure. More so than most people realize! Graphs can be used to model practically anything, given their nature of...

David Landup

Data Visualization in Python with Matplotlib and Pandas

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

© 2013- 2024 Stack Abuse. All rights reserved.

Python Slicing – How to Slice an Array and What Does [::-1] Mean?

Dillion Megida

Slicing an array is the concept of cutting out – or slicing out – a part of the array. How do you do this in Python? I'll show you how in this article.

If you like watching video content to supplement your reading, here's a video version of this article as well.

What is an Array?

An array is a data structure that allows you to store multiple items of the same data type in order in a variable at the same time. You can access each of these items by their index (location in the order).

They are a bit similar to lists in Python, it's just that lists allow you to store multiple items of different data types . Also, while lists are built-in, arrays aren't.

How to Access Values in an Array in Python

Here's the syntax to create an array in Python:

As the array data type is not built into Python by default, you have to import it from the array module. We import this module as arr .

Using the array method of arr , we can create an array by specifying a typecode (data type of the values) and the values stored in the array.

Here's a table showing the acceptable typecodes:

Typecodes gotten from the Python documentation .

Here's an example array in Python:

We created an array of integer values from 1 to 5 here. We also accessed the second value by using square brackets and its index in the order, which is 1 .

How to Slice an Array in Python

Let's say you want to slice a portion of this array and assign the slice to another variable. You can do it using colons and square brackets. The syntax looks like this:

The start index specifies the index that the slicing starts from. The default is 0 .

The end index specifies the index where the slicing ends (but excluding the value at this index). The default is the length of the array.

The step argument specifies the step of the slicing. The default is 1 .

Let's see some examples that cover different ways in which arrays can be sliced.

How to slice without a start or end index

When you slice without a start or end index, you basically get a whole copy of the array:

As you can see here, we have a copy of the numbers array.

It's also worth noting that the slicing action does not affect the original array. With slicing, you only "copy a portion" of the original array.

How to slice with a start index

For example, if you want to slice an array from a specific start value to the end of the array, here's how:

By passing 2: in the square brackets, the slicing starts from index 2 (which holds value 3) up until the end of the array, as you can see in the results.

How to slice with an end index

For example, if you want to slice an array from the first value to the third, here's how:

By passing :3 in the square brackets, slicing starts from the 0 index (by default, since not specified) up until the third index we specified.

As mentioned earlier, the slicing excludes the value at the third index. So in the results, as you find in the copy variable, the values returned are from index 0 through index 2 .

How to slice with a start and end index

What if you want to specify the starting and ending points of the slicing? Here's how:

By using a number, then a colon, followed by a number in square brackets, you can specify a starting and ending indexes, respectively.

In our case, we used 1 and 4 as in [1:4] . From the results, you see that the slicing starts from the value at index 1 which is 2 , up until the value before the index 4 , which is 4 (at index 3).

How to slice with steps

When you specify a start and end index of 1 and 5, respectively, slicing will select values at index 1 , index 2 (1 increment to the previous index), index 3 (1 increment to the previous index) and index 4 (and one increment to the previous index).

In this slicing, a step of 1 is used by default. But you can provide a different step. Here's how:

By adding another colon, you can specify a step. So we have [start:stop:step] .

In our example, the start is 1 , the end is 4 and the step is 2. Slicing starts from the value at index 1 which is 2 , then the next value will be at the previous index plus the step, which is 1 + 2 equals 3. The value at index 3 is 4 so that is added to the slice. The next index will be 5 ( 3 + 2 ) but since 5 exceeds the stop index, it will not be added to the slice.

As you can see in the code, the sliced copy is just 2 and 4.

How to slice with negative start and end indexes

The start or stop indexes can also be negative. Negative indexes count from the end of the array. This means a negative index is the last value in an array:

By using a negative 1 here, you see that 5 is returned, which is from the end of an array.

With a slice expression like [-3:-1] , this means a start index of -3 and end index of -1 . Let's see how that works with our array:

The slice starts from index -3 (which is the third value from the end of the array, that is 3) and stops at index -1 (which is the last value in the array, that is 5). Slicing doesn't include the last value so we have 3 and 4.

Combining a negative start index and a positive end index (or vice versa) will not work as you'll be going different directions at once.

How to slice with negative steps

You can use negative steps, which means the steps decrement for the slicing. Here's an example:

Here, we specify a start of index 2 , no end, and a step of -1 . Slicing here will start from index 2 which is 3. The negative steps mean the next value in the slice will be at an index smaller than the previous index by 1. This means 2 - 1 which is 1 so the value at this index, which is 2 will be added to the slice.

This goes on reversed until it gets to the end of the array which is index 0 . The sliced array results in values of 3, 2, and 1.

What does [::-1] mean?

Have you seen this expression anywhere in Python before? Well, here's what it means: there's no start index specified, nor an end index, only a negative step of -1 .

The start index defaults to 0 , so by using -1 step, the slicing will contain values at the following indexes: -1 ( 0 - 1 ), -2 ( -1 - 1 ), -3 ( -2 - 1 ), -4 ( -3 - 1 ) and -5 ( -4 - 1 ). Pretty much a reversed copy of the array.

Here's the code for it:

As you can see, this is a simple way to reverse an array.

Wrapping Up

In this article, we've briefly looked at how to declare arrays in Python, how to access values in an array, and also how to cut – or slice – a part of an array using a colon and square brackets.

We also learned how slicing works with steps and positive/negative start and stop indexes.

You can learn more about arrays here: Python Array Tutorial – Define, Index, Methods .

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics

Python List

  • Python Tuple
  • Python String
  • Python Sets
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python Matrices and NumPy Arrays

Python Numbers, Type Conversion and Mathematics

Python bytearray()

  • Python Data Types
  • Python bytes()

Python Array

In this tutorial, we will focus on a module named array . The array module allows us to store a collection of numeric values.

Note: When people say arrays in Python, more often than not, they are talking about Python lists . If that's the case, visit the Python list tutorial.

  • Creating Python Arrays

To create an array of numeric values, we need to import the array module. For example:

Here, we created an array of float type. The letter d is a type code. This determines the type of the array during creation.

Commonly used type codes are listed as follows:

We will not discuss different C types in this article. We will use two type codes in this entire article: i for integers and d for floats.

Note : The u type code for Unicode characters is deprecated since version 3.3. Avoid using as much as possible.

  • Accessing Python Array Elements

We use indices to access elements of an array:

Note : The index starts from 0 (not 1) similar to lists.

  • Slicing Python Arrays

We can access a range of items in an array by using the slicing operator : .

  • Changing and Adding Elements

Arrays are mutable; their elements can be changed in a similar way as lists.

We can add one item to the array using the append() method, or add several items using the extend() method.

We can also concatenate two arrays using + operator.

  • Removing Python Array Elements

We can delete one or more items from an array using Python's del statement.

We can use the remove() method to remove the given item, and pop() method to remove an item at the given index.

Check this page to learn more about Python array and array methods .

  • Python Lists Vs Arrays

In Python, we can treat lists as arrays. However, we cannot constrain the type of elements stored in a list. For example:

If you create arrays using the array module, all elements of the array must be of the same numeric type.

  • When to use arrays?

Lists are much more flexible than arrays. They can store elements of different data types including strings. And, if you need to do mathematical computation on arrays and matrices, you are much better off using something like NumPy .

So, what are the uses of arrays created from the Python array module?

The array.array type is just a thin wrapper on C arrays which provides space-efficient storage of basic C-style data types. If you need to allocate an array that you know will not change, then arrays can be faster and use less memory than lists.

Unless you don't really need arrays (array module may be needed to interface with C code), the use of the array module is not recommended.

Table of Contents

  • Introduction

Sorry about that.

Related Tutorials

Python Tutorial

Python Library

numpy.array #

Create an array.

An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. If object is a scalar, a 0-dimensional array containing object is returned.

The desired data-type for the array. If not given, NumPy will try to use a default dtype that can represent the values (by applying promotion rules when necessary.)

If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements ( dtype , order , etc.).

Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless ‘F’ is specified, in which case it will be in Fortran order (column major). If object is an array the following holds.

When copy=False and a copy is made for other reasons, the result is the same as if copy=True , with some exceptions for ‘A’, see the Notes section. The default order is ‘K’.

If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).

Specifies the minimum number of dimensions that the resulting array should have. Ones will be prepended to the shape as needed to meet this requirement.

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

New in version 1.20.0.

An array object satisfying the specified requirements.

Return an empty array with shape and type of input.

Return an array of ones with shape and type of input.

Return an array of zeros with shape and type of input.

Return a new array with shape of input filled with value.

Return a new uninitialized array.

Return a new array setting values to one.

Return a new array setting values to zero.

Return a new array of given shape filled with value.

When order is ‘A’ and object is an array in neither ‘C’ nor ‘F’ order, and a copy is forced by a change in dtype, then the order of the result is not necessarily ‘C’ as expected. This is likely a bug.

More than one dimension:

Minimum dimensions 2:

Type provided:

Data-type consisting of more than one element:

Creating an array from sub-classes:

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Operators

Precedence and associativity of operators in python.

  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic

Ternary Operator in Python

  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity Operators and Membership Operators

Python Operators

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication , and division .

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Example of Arithmetic Operators in Python

Division operators.

In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. 

There are two types of division operators: 

Float division

  • Floor division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’ , and ‘-10/2’ results in ‘-5.0’ .

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python operators . It provides results as follows: ’10//3′ equals ‘3’ , ‘-5//2’ equals ‘-3’ , ‘ 5.0//2′ equals ‘2.0’ , and ‘-5.0//2’ equals ‘-3.0’ . Integer division returns the largest integer less than or equal to the division result.

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication (Multiplication and division have the same precedence)
  • D – Division
  • A – Addition (Addition and subtraction have the same precedence)
  • S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’ . It adds (‘+’) , subtracts (‘-‘) , multiplies (‘*’) , computes the remainder (‘%’) , and raises a to the power of ‘b (**)’ . The results of these operations are printed.

Note: Refer to Differences between / and // for some interesting facts about these two Python operators.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’ .

Logical Operators in Python

Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  • Logical not
  • logical and

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true ( ‘and’ ), if at least one of them is true ( ‘or’ ), and negates the value of ‘a’ using ‘not’ . The results are printed accordingly.

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  • Bitwise NOT
  • Bitwise Shift
  • Bitwise AND
  • Bitwise XOR

Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’ . It performs bitwise AND (&) , OR (|) , NOT (~) , XOR (^) , right shift (>>) , and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.

Python Assignment operators are used to assign values to the variables.

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’ . The results of each operation are printed, showing the impact of these operations on the value of ‘b’ .

Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. 

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’ ).

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :   [on_true] if [expression] else [on_false] 

Examples of Ternary Operator in Python

The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’ . Finally, it prints the value of ‘min’ , which is 10 in this case.

In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Let’s see an example of how Operator Precedence in Python works:

Example: The code first calculates and prints the value of the expression 10 + 20 * 30 , which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “ Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”

Operator Associativity in Python

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

The following code shows how Operator Associativity in Python works:

Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.

To try your knowledge of Python Operators, you can take out the quiz on Operators in Python . 

Python Operator Exercise Questions

Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.

Q1. Code to implement basic arithmetic operations on integers

Q2. Code to implement Comparison operations on integers

Explore more Exercises: Practice Exercise on Operators in Python

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

COMMENTS

  1. How do I declare an array in Python?

    A couple of contributions suggested that arrays in python are represented by lists. This is incorrect. Python has an independent implementation of array() in the standard library module array "array.array()" hence it is incorrect to confuse the two. Lists are lists in python so be careful with the nomenclature used.

  2. Python Arrays

    Array Methods. Python has a set of built-in methods that you can use on lists/arrays. Note: Python does not have built-in support for Arrays, but Python Lists can be used instead. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  3. Python's Array: Working With Numeric Data Efficiently

    Keep Learning. In this tutorial, you'll dive deep into working with numeric arrays in Python, an efficient tool for handling binary data. Along the way, you'll explore low-level data types exposed by the array module, emulate custom types, and even pass a Python array to C for high-performance processing.

  4. array

    This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single ...

  5. NumPy Indexing and Assignment

    Element Assignment in NumPy Arrays. We can assign new values to an element of a NumPy array using the = operator, just like regular python lists. A few examples are below (note that this is all one code block, which means that the element assignments are carried forward from step to step). array([0.12, 0.94, 0.66, 0.73, 0.83])

  6. Python Array Tutorial

    That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type. ... You can change the value of a specific element by speficying its position and assigning it a new value: import array as arr #original array numbers = arr.array('i',[10,20,30]) #change ...

  7. How Arrays Work in Python

    Python Array Methods. You can use various built-in Python methods when working with lists and arrays. Below are the methods you can use on arrays and lists in Python. The Append() method. If you want to add an item to the end of a list, you can utilize the append method. Example:

  8. Guide to Arrays in Python

    While the array module offers a more memory-efficient way to store basic data types, it's essential to remember its limitations.Unlike lists, arrays are homogeneous.This means all elements in the array must be of the same type. Also, you can only store basic C-style data types in arrays. If you need to store custom objects or other Python types, you'll need to use a list or another data structure.

  9. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

  10. Declaring an Array in Python

    Syntax to Declare an array. Variable_Name = array (typecode, [element1, element2, …., elementn]) Here, Variable_Name - It is the name of an array. typecode - It specifies the type of elements to be stored in an array. [] - Inside square bracket we can mention the element to be stored in array while declaration.

  11. Python Slicing

    How to Slice an Array in Python. Let's say you want to slice a portion of this array and assign the slice to another variable. You can do it using colons and square brackets. The syntax looks like this: array[start:stop:step] The start index specifies the index that the slicing starts from. The default is 0.

  12. Structured arrays

    Indexing and Assignment to Structured arrays# Assigning data to a Structured Array# There are a number of ways to assign values to a structured array: Using python tuples, using scalar values, or using other structured arrays. Assignment from Python Native Types (Tuples)# The simplest way to assign values to a structured array is using python ...

  13. Python Array of Numeric Values

    Note: When people say arrays in Python, more often than not, they are talking about Python lists. If that's the case, visit the Python list tutorial. Creating Python Arrays. To create an array of numeric values, we need to import the array module. For example:

  14. Python Arrays

    Complexities for Removing elements in the Arrays. Time Complexity: O(1)/O(n) ( O(1) - for removing elements at the end of the array, O(n) - for removing elements at the beginning of the Python create array and to the full array Auxiliary Space: O(1) Slicing of an Array. In Python array, there are multiple ways to print the whole array with all the elements, but to print a specific range of ...

  15. python

    Use numpy.meshgrid () to make arrays of indexes that you can use to index into both your original array and the array of values for the third dimension. import numpy as np. import scipy as sp. import scipy.stats.distributions. a = np.zeros((2,3,4)) z = sp.stats.distributions.randint.rvs(0, 4, size=(2,3))

  16. Indexing on ndarrays

    ndarrays. #. ndarrays can be indexed using the standard Python x[obj] syntax, where x is the array and obj the selection. There are different kinds of indexing available depending on obj : basic indexing, advanced indexing and field access. Most of the following examples show the use of indexing when referencing data in an array.

  17. Array creation

    There are 6 general mechanisms for creating arrays: Conversion from other Python structures (i.e. lists and tuples) Intrinsic NumPy array creation functions (e.g. arange, ones, zeros, etc.) Replicating, joining, or mutating existing arrays. Reading arrays from disk, either from standard or custom formats. Creating arrays from raw bytes through ...

  18. Assign value to an individual cell in a two dimensional python array

    Let's say I have the following empty two dimensional array in Python: q = [[None]*5]*4 I want to assign a value of 5 to the first row in the first column of q. Instinctively, I do the following: q[0][0] = 5 However, this produces:

  19. numpy.array

    Create an array. Parameters: object array_like. An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. If object is a scalar, a 0-dimensional array containing object is returned. dtype data-type, optional. The desired data-type for the array.

  20. Look Ma, No for Loops: Array Programming With NumPy

    An instructive first step is to visualize, given the patch size and image shape, what a higher-dimensional array of patches would look like. We have a 2d array img with shape (254, 319) and a (10, 10) 2d patch. This means our output shape (before taking the mean of each "inner" 10x10 array) would be: Python.

  21. Python Operators

    Assignment Operators in Python. Let's see an example of Assignment Operators in Python. Example: The code starts with 'a' and 'b' both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on 'b'.

  22. Python array assignments

    1. The problem that you are having is that objects in python are pass by reference meaning that when you think you've copied it, it's really just a shadow of the original and any changes get reflected back. You need to use numpy.copy() The pythonic way to clone an array is by slicing: b = a[:]