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.

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.

Method Description
Adds an element at the end of the list
Removes all the elements from the list
Returns a copy of the list
Returns the number of elements with the specified value
Add the elements of a list (or any iterable), to the end of the current list
Returns the index of the first element with the specified value
Adds an element at the specified position
Removes the element at the specified position
Removes the first item with the specified value
Reverses the order of the list
Sorts the list

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's Assignment Operator: Write Robust Assignments

Python's Assignment Operator: Write Robust Assignments

Table of Contents

The Assignment Statement Syntax

The assignment operator, assignments and variables, other assignment syntax, initializing and updating variables, making multiple variables refer to the same object, updating lists through indices and slices, adding and updating dictionary keys, doing parallel assignments, unpacking iterables, providing default argument values, augmented mathematical assignment operators, augmented assignments for concatenation and repetition, augmented bitwise assignment operators, annotated assignment statements, assignment expressions with the walrus operator, managed attribute assignments, define or call a function, work with classes, import modules and objects, use a decorator, access the control variable in a for loop or a comprehension, use the as keyword, access the _ special variable in an interactive session, built-in objects, named constants.

Python’s assignment operators allow you to define assignment statements . This type of statement lets you create, initialize, and update variables throughout your code. Variables are a fundamental cornerstone in every piece of code, and assignment statements give you complete control over variable creation and mutation.

Learning about the Python assignment operator and its use for writing assignment statements will arm you with powerful tools for writing better and more robust Python code.

In this tutorial, you’ll:

  • Use Python’s assignment operator to write assignment statements
  • Take advantage of augmented assignments in Python
  • Explore assignment variants, like assignment expressions and managed attributes
  • Become aware of illegal and dangerous assignments in Python

You’ll dive deep into Python’s assignment statements. To get the most out of this tutorial, you should be comfortable with several basic topics, including variables , built-in data types , comprehensions , functions , and Python keywords . Before diving into some of the later sections, you should also be familiar with intermediate topics, such as object-oriented programming , constants , imports , type hints , properties , descriptors , and decorators .

Free Source Code: Click here to download the free assignment operator source code that you’ll use to write assignment statements that allow you to create, initialize, and update variables in your code.

Assignment Statements and the Assignment Operator

One of the most powerful programming language features is the ability to create, access, and mutate variables . In Python, a variable is a name that refers to a concrete value or object, allowing you to reuse that value or object throughout your code.

To create a new variable or to update the value of an existing one in Python, you’ll use an assignment statement . This statement has the following three components:

  • A left operand, which must be a variable
  • The assignment operator ( = )
  • A right operand, which can be a concrete value , an object , or an expression

Here’s how an assignment statement will generally look in Python:

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 . This value will live at a specific memory address in your computer.
  • Store the object’s memory address in the left-hand variable . This step creates a new variable if the current one doesn’t already exist or updates the value of an existing variable.

The second step shows that variables work differently in Python than in other programming languages. In Python, variables aren’t containers for objects. Python variables point to a value or object through its memory address. They store memory addresses rather than objects.

This behavior difference directly impacts how data moves around in Python, which is always by reference . In most cases, this difference is irrelevant in your day-to-day coding, but it’s still good to know.

The central component of an assignment statement is the assignment operator . This operator is represented by the = symbol, which separates two operands:

  • A value or an expression that evaluates to a concrete value

Operators are special symbols that perform mathematical , logical , and bitwise operations in a programming language. The objects (or object) on which an operator operates are called operands .

Unary operators, like the not Boolean operator, operate on a single object or operand, while binary operators act on two. That means the assignment operator is a binary operator.

Note: Like C , Python uses == for equality comparisons and = for assignments. Unlike C, Python doesn’t allow you to accidentally use the assignment operator ( = ) in an equality comparison.

Equality is a symmetrical relationship, and assignment is not. For example, the expression a == 42 is equivalent to 42 == a . In contrast, the statement a = 42 is correct and legal, while 42 = a isn’t allowed. You’ll learn more about illegal assignments later on.

The right-hand operand in an assignment statement can be any Python object, such as a number , list , string , dictionary , or even a user-defined object. It can also be an expression. In the end, expressions always evaluate to concrete objects, which is their return value.

Here are a few examples of assignments in Python:

The first two sample assignments in this code snippet use concrete values, also known as literals , to create and initialize number and greeting . The third example assigns the result of a math expression to the total variable, while the last example uses a Boolean expression.

Note: You can use the built-in id() function to inspect the memory address stored in a given variable.

Here’s a short example of how this function works:

The number in your output represents the memory address stored in number . Through this address, Python can access the content of number , which is the integer 42 in this example.

If you run this code on your computer, then you’ll get a different memory address because this value varies from execution to execution and computer to computer.

Unlike expressions, assignment statements don’t have a return value because their purpose is to make the association between the variable and its value. That’s why the Python interpreter doesn’t issue any output in the above examples.

Now that you know the basics of how to write an assignment statement, it’s time to tackle why you would want to use one.

The assignment statement is the explicit way for you to associate a name with an object in Python. You can use this statement for two main purposes:

  • Creating and initializing new variables
  • Updating the values of existing variables

When you use a variable name as the left operand in an assignment statement for the first time, you’re creating a new variable. At the same time, you’re initializing the variable to point to the value of the right operand.

On the other hand, when you use an existing variable in a new assignment, you’re updating or mutating the variable’s value. Strictly speaking, every new assignment will make the variable refer to a new value and stop referring to the old one. Python will garbage-collect all the values that are no longer referenced by any existing variable.

Assignment statements not only assign a value to a variable but also determine the data type of the variable at hand. This additional behavior is another important detail to consider in this kind of statement.

Because Python is a dynamically typed language, successive assignments to a given variable can change the variable’s data type. Changing the data type of a variable during a program’s execution is considered bad practice and highly discouraged. It can lead to subtle bugs that can be difficult to track down.

Unlike in math equations, in Python assignments, the left operand must be a variable rather than an expression or a value. For example, the following construct is illegal, and Python flags it as invalid syntax:

In this example, you have expressions on both sides of the = sign, and this isn’t allowed in Python code. The error message suggests that you may be confusing the equality operator with the assignment one, but that’s not the case. You’re really running an invalid assignment.

To correct this construct and convert it into a valid assignment, you’ll have to do something like the following:

In this code snippet, you first import the sqrt() function from the math module. Then you isolate the hypotenuse variable in the original equation by using the sqrt() function. Now your code works correctly.

Now you know what kind of syntax is invalid. But don’t get the idea that assignment statements are rigid and inflexible. In fact, they offer lots of room for customization, as you’ll learn next.

Python’s assignment statements are pretty flexible and versatile. You can write them in several ways, depending on your specific needs and preferences. Here’s a quick summary of the main ways to write assignments in Python:

Up to this point, you’ve mostly learned about the base assignment syntax in the above code snippet. In the following sections, you’ll learn about multiple, parallel, and augmented assignments. You’ll also learn about assignments with iterable unpacking.

Read on to see the assignment statements in action!

Assignment Statements in Action

You’ll find and use assignment statements everywhere in your Python code. They’re a fundamental part of the language, providing an explicit way to create, initialize, and mutate variables.

You can use assignment statements with plain names, like number or counter . You can also use assignments in more complicated scenarios, such as with:

  • Qualified attribute names , like user.name
  • Indices and slices of mutable sequences, like a_list[i] and a_list[i:j]
  • Dictionary keys , like a_dict[key]

This list isn’t exhaustive. However, it gives you some idea of how flexible these statements are. You can even assign multiple values to an equal number of variables in a single line, commonly known as parallel assignment . Additionally, you can simultaneously assign the values in an iterable to a comma-separated group of variables in what’s known as an iterable unpacking operation.

In the following sections, you’ll dive deeper into all these topics and a few other exciting things that you can do with assignment statements in Python.

The most elementary use case of an assignment statement is to create a new variable and initialize it using a particular value or expression:

All these statements create new variables, assigning them initial values or expressions. For an initial value, you should always use the most sensible and least surprising value that you can think of. For example, initializing a counter to something different from 0 may be confusing and unexpected because counters almost always start having counted no objects.

Updating a variable’s current value or state is another common use case of assignment statements. In Python, assigning a new value to an existing variable doesn’t modify the variable’s current value. Instead, it causes the variable to refer to a different value. The previous value will be garbage-collected if no other variable refers to it.

Consider the following examples:

These examples run two consecutive assignments on the same variable. The first one assigns the string "Hello, World!" to a new variable named greeting .

The second assignment updates the value of greeting by reassigning it the "Hi, Pythonistas!" string. In this example, the original value of greeting —the "Hello, World!" string— is lost and garbage-collected. From this point on, you can’t access the old "Hello, World!" string.

Even though running multiple assignments on the same variable during a program’s execution is common practice, you should use this feature with caution. Changing the value of a variable can make your code difficult to read, understand, and debug. To comprehend the code fully, you’ll have to remember all the places where the variable was changed and the sequential order of those changes.

Because assignments also define the data type of their target variables, it’s also possible for your code to accidentally change the type of a given variable at runtime. A change like this can lead to breaking errors, like AttributeError exceptions. Remember that strings don’t have the same methods and attributes as lists or dictionaries, for example.

In Python, you can make several variables reference the same object in a multiple-assignment line. This can be useful when you want to initialize several similar variables using the same initial value:

In this example, you chain two assignment operators in a single line. This way, your two variables refer to the same initial value of 0 . Note how both variables hold the same memory address, so they point to the same instance of 0 .

When it comes to integer variables, Python exhibits a curious behavior. It provides a numeric interval where multiple assignments behave the same as independent assignments. Consider the following examples:

To create n and m , you use independent assignments. Therefore, they should point to different instances of the number 42 . However, both variables hold the same object, which you confirm by comparing their corresponding memory addresses.

Now check what happens when you use a greater initial value:

Now n and m hold different memory addresses, which means they point to different instances of the integer number 300 . In contrast, when you use multiple assignments, both variables refer to the same object. This tiny difference can save you small bits of memory if you frequently initialize integer variables in your code.

The implicit behavior of making independent assignments point to the same integer number is actually an optimization called interning . It consists of globally caching the most commonly used integer values in day-to-day programming.

Under the hood, Python defines a numeric interval in which interning takes place. That’s the interning interval for integer numbers. You can determine this interval using a small script like the following:

This script helps you determine the interning interval by comparing integer numbers from -10 to 500 . If you run the script from your command line, then you’ll get an output like the following:

This output means that if you use a single number between -5 and 256 to initialize several variables in independent statements, then all these variables will point to the same object, which will help you save small bits of memory in your code.

In contrast, if you use a number that falls outside of the interning interval, then your variables will point to different objects instead. Each of these objects will occupy a different memory spot.

You can use the assignment operator to mutate the value stored at a given index in a Python list. The operator also works with list slices . The syntax to write these types of assignment statements is the following:

In the first construct, expression can return any Python object, including another list. In the second construct, expression must return a series of values as a list, tuple, or any other sequence. You’ll get a TypeError if expression returns a single value.

Note: When creating slice objects, you can use up to three arguments. These arguments are start , stop , and step . They define the number that starts the slice, the number at which the slicing must stop retrieving values, and the step between values.

Here’s an example of updating an individual value in a list:

In this example, you update the value at index 2 using an assignment statement. The original number at that index was 7 , and after the assignment, the number is 3 .

Note: Using indices and the assignment operator to update a value in a tuple or a character in a string isn’t possible because tuples and strings are immutable data types in Python.

Their immutability means that you can’t change their items in place :

You can’t use the assignment operator to change individual items in tuples or strings. These data types are immutable and don’t support item assignments.

It’s important to note that you can’t add new values to a list by using indices that don’t exist in the target list:

In this example, you try to add a new value to the end of numbers by using an index that doesn’t exist. This assignment isn’t allowed because there’s no way to guarantee that new indices will be consecutive. If you ever want to add a single value to the end of a list, then use the .append() method.

If you want to update several consecutive values in a list, then you can use slicing and an assignment statement:

In the first example, you update the letters between indices 1 and 3 without including the letter at 3 . The second example updates the letters from index 3 until the end of the list. Note that this slicing appends a new value to the list because the target slice is shorter than the assigned values.

Also note that the new values were provided through a tuple, which means that this type of assignment allows you to use other types of sequences to update your target list.

The third example updates a single value using a slice where both indices are equal. In this example, the assignment inserts a new item into your target list.

In the final example, you use a step of 2 to replace alternating letters with their lowercase counterparts. This slicing starts at index 1 and runs through the whole list, stepping by two items each time.

Updating the value of an existing key or adding new key-value pairs to a dictionary is another common use case of assignment statements. To do these operations, you can use the following syntax:

The first construct helps you update the current value of an existing key, while the second construct allows you to add a new key-value pair to the dictionary.

For example, to update an existing key, you can do something like this:

In this example, you update the current inventory of oranges in your store using an assignment. The left operand is the existing dictionary key, and the right operand is the desired new value.

While you can’t add new values to a list by assignment, dictionaries do allow you to add new key-value pairs using the assignment operator. In the example below, you add a lemon key to inventory :

In this example, you successfully add a new key-value pair to your inventory with 100 units. This addition is possible because dictionaries don’t have consecutive indices but unique keys, which are safe to add by assignment.

The assignment statement does more than assign the result of a single expression to a single variable. It can also cope nicely with assigning multiple values to multiple variables simultaneously in what’s known as a parallel assignment .

Here’s the general syntax for parallel assignments in Python:

Note that the left side of the statement can be either a tuple or a list of variables. Remember that to create a tuple, you just need a series of comma-separated elements. In this case, these elements must be variables.

The right side of the statement must be a sequence or iterable of values or expressions. In any case, the number of elements in the right operand must match the number of variables on the left. Otherwise, you’ll get a ValueError exception.

In the following example, you compute the two solutions of a quadratic equation using a parallel assignment:

In this example, you first import sqrt() from the math module. Then you initialize the equation’s coefficients in a parallel assignment.

The equation’s solution is computed in another parallel assignment. The left operand contains a tuple of two variables, x1 and x2 . The right operand consists of a tuple of expressions that compute the solutions for the equation. Note how each result is assigned to each variable by position.

A classical use case of parallel assignment is to swap values between variables:

The highlighted line does the magic and swaps the values of previous_value and next_value at the same time. Note that in a programming language that doesn’t support this kind of assignment, you’d have to use a temporary variable to produce the same effect:

In this example, instead of using parallel assignment to swap values between variables, you use a new variable to temporarily store the value of previous_value to avoid losing its reference.

For a concrete example of when you’d need to swap values between variables, say you’re learning how to implement the bubble sort algorithm , and you come up with the following function:

In the highlighted line, you use a parallel assignment to swap values in place if the current value is less than the next value in the input list. To dive deeper into the bubble sort algorithm and into sorting algorithms in general, check out Sorting Algorithms in Python .

You can use assignment statements for iterable unpacking in Python. Unpacking an iterable means assigning its values to a series of variables one by one. The iterable must be the right operand in the assignment, while the variables must be the left operand.

Like in parallel assignments, the variables must come as a tuple or list. The number of variables must match the number of values in the iterable. Alternatively, you can use the unpacking operator ( * ) to grab several values in a variable if the number of variables doesn’t match the iterable length.

Here’s the general syntax for iterable unpacking in Python:

Iterable unpacking is a powerful feature that you can use all around your code. It can help you write more readable and concise code. For example, you may find yourself doing something like this:

Whenever you do something like this in your code, go ahead and replace it with a more readable iterable unpacking using a single and elegant assignment, like in the following code snippet:

The numbers list on the right side contains four values. The assignment operator unpacks these values into the four variables on the left side of the statement. The values in numbers get assigned to variables in the same order that they appear in the iterable. The assignment is done by position.

Note: Because Python sets are also iterables, you can use them in an iterable unpacking operation. However, it won’t be clear which value goes to which variable because sets are unordered data structures.

The above example shows the most common form of iterable unpacking in Python. The main condition for the example to work is that the number of variables matches the number of values in the iterable.

What if you don’t know the iterable length upfront? Will the unpacking work? It’ll work if you use the * operator to pack several values into one of your target variables.

For example, say that you want to unpack the first and second values in numbers into two different variables. Additionally, you would like to pack the rest of the values in a single variable conveniently called rest . In this case, you can use the unpacking operator like in the following code:

In this example, first and second hold the first and second values in numbers , respectively. These values are assigned by position. The * operator packs all the remaining values in the input iterable into rest .

The unpacking operator ( * ) can appear at any position in your series of target variables. However, you can only use one instance of the operator:

The iterable unpacking operator works in any position in your list of variables. Note that you can only use one unpacking operator per assignment. Using more than one unpacking operator isn’t allowed and raises a SyntaxError .

Dropping away unwanted values from the iterable is a common use case for the iterable unpacking operator. Consider the following example:

In Python, if you want to signal that a variable won’t be used, then you use an underscore ( _ ) as the variable’s name. In this example, useful holds the only value that you need to use from the input iterable. The _ variable is a placeholder that guarantees that the unpacking works correctly. You won’t use the values that end up in this disposable variable.

Note: In the example above, if your target iterable is a sequence data type, such as a list or tuple, then it’s best to access its last item directly.

To do this, you can use the -1 index:

Using -1 gives you access to the last item of any sequence data type. In contrast, if you’re dealing with iterators , then you won’t be able to use indices. That’s when the *_ syntax comes to your rescue.

The pattern used in the above example comes in handy when you have a function that returns multiple values, and you only need a few of these values in your code. The os.walk() function may provide a good example of this situation.

This function allows you to iterate over the content of a directory recursively. The function returns a generator object that yields three-item tuples. Each tuple contains the following items:

  • The path to the current directory as a string
  • The names of all the immediate subdirectories as a list of strings
  • The names of all the files in the current directory as a list of strings

Now say that you want to iterate over your home directory and list only the files. You can do something like this:

This code will issue a long output depending on the current content of your home directory. Note that you need to provide a string with the path to your user folder for the example to work. The _ placeholder variable will hold the unwanted data.

In contrast, the filenames variable will hold the list of files in the current directory, which is the data that you need. The code will print the list of filenames. Go ahead and give it a try!

The assignment operator also comes in handy when you need to provide default argument values in your functions and methods. Default argument values allow you to define functions that take arguments with sensible defaults. These defaults allow you to call the function with specific values or to simply rely on the defaults.

As an example, consider the following function:

This function takes one argument, called name . This argument has a sensible default value that’ll be used when you call the function without arguments. To provide this sensible default value, you use an assignment.

Note: According to PEP 8 , the style guide for Python code, you shouldn’t use spaces around the assignment operator when providing default argument values in function definitions.

Here’s how the function works:

If you don’t provide a name during the call to greet() , then the function uses the default value provided in the definition. If you provide a name, then the function uses it instead of the default one.

Up to this point, you’ve learned a lot about the Python assignment operator and how to use it for writing different types of assignment statements. In the following sections, you’ll dive into a great feature of assignment statements in Python. You’ll learn about augmented assignments .

Augmented Assignment Operators in Python

Python supports what are known as augmented assignments . An augmented assignment combines the assignment operator with another operator to make the statement more concise. Most Python math and bitwise operators have an augmented assignment variation that looks something like this:

Note that $ isn’t a valid Python operator. In this example, it’s a placeholder for a generic operator. This statement works as follows:

  • Evaluate expression to produce a value.
  • Run the operation defined by the operator that prefixes the = sign, using the previous value of variable and the return value of expression as operands.
  • Assign the resulting value back to variable .

In practice, an augmented assignment like the above is equivalent to the following statement:

As you can conclude, augmented assignments are syntactic sugar . They provide a shorthand notation for a specific and popular kind of assignment.

For example, say that you need to define a counter variable to count some stuff in your code. You can use the += operator to increment counter by 1 using the following code:

In this example, the += operator, known as augmented addition , adds 1 to the previous value in counter each time you run the statement counter += 1 .

It’s important to note that unlike regular assignments, augmented assignments don’t create new variables. They only allow you to update existing variables. If you use an augmented assignment with an undefined variable, then you get a NameError :

Python evaluates the right side of the statement before assigning the resulting value back to the target variable. In this specific example, when Python tries to compute x + 1 , it finds that x isn’t defined.

Great! You now know that an augmented assignment consists of combining the assignment operator with another operator, like a math or bitwise operator. To continue this discussion, you’ll learn which math operators have an augmented variation in Python.

An equation like x = x + b doesn’t make sense in math. But in programming, a statement like x = x + b is perfectly valid and can be extremely useful. It adds b to x and reassigns the result back to x .

As you already learned, Python provides an operator to shorten x = x + b . Yes, the += operator allows you to write x += b instead. Python also offers augmented assignment operators for most math operators. Here’s a summary:

Operator Description Example Equivalent
Adds the right operand to the left operand and stores the result in the left operand
Subtracts the right operand from the left operand and stores the result in the left operand
Multiplies the right operand with the left operand and stores the result in the left operand
Divides the left operand by the right operand and stores the result in the left operand
Performs of the left operand by the right operand and stores the result in the left operand
Finds the remainder of dividing the left operand by the right operand and stores the result in the left operand
Raises the left operand to the power of the right operand and stores the result in the left operand

The Example column provides generic examples of how to use the operators in actual code. Note that x must be previously defined for the operators to work correctly. On the other hand, y can be either a concrete value or an expression that returns a value.

Note: The matrix multiplication operator ( @ ) doesn’t support augmented assignments yet.

Consider the following example of matrix multiplication using NumPy arrays:

Note that the exception traceback indicates that the operation isn’t supported yet.

To illustrate how augmented assignment operators work, say that you need to create a function that takes an iterable of numeric values and returns their sum. You can write this function like in the code below:

In this function, you first initialize total to 0 . In each iteration, the loop adds a new number to total using the augmented addition operator ( += ). When the loop terminates, total holds the sum of all the input numbers. Variables like total are known as accumulators . The += operator is typically used to update accumulators.

Note: Computing the sum of a series of numeric values is a common operation in programming. Python provides the built-in sum() function for this specific computation.

Another interesting example of using an augmented assignment is when you need to implement a countdown while loop to reverse an iterable. In this case, you can use the -= operator:

In this example, custom_reversed() is a generator function because it uses yield . Calling the function creates an iterator that yields items from the input iterable in reverse order. To decrement the control variable, index , you use an augmented subtraction statement that subtracts 1 from the variable in every iteration.

Note: Similar to summing the values in an iterable, reversing an iterable is also a common requirement. Python provides the built-in reversed() function for this specific computation, so you don’t have to implement your own. The above example only intends to show the -= operator in action.

Finally, counters are a special type of accumulators that allow you to count objects. Here’s an example of a letter counter:

To create this counter, you use a Python dictionary. The keys store the letters. The values store the counts. Again, to increment the counter, you use an augmented addition.

Counters are so common in programming that Python provides a tool specially designed to facilitate the task of counting. Check out Python’s Counter: The Pythonic Way to Count Objects for a complete guide on how to use this tool.

The += and *= augmented assignment operators also work with sequences , such as lists, tuples, and strings. The += operator performs augmented concatenations , while the *= operator performs augmented repetition .

These operators behave differently with mutable and immutable data types:

Operator Description Example
Runs an augmented concatenation operation on the target sequence. Mutable sequences are updated in place. If the sequence is immutable, then a new sequence is created and assigned back to the target name.
Adds to itself times. Mutable sequences are updated in place. If the sequence is immutable, then a new sequence is created and assigned back to the target name.

Note that the augmented concatenation operator operates on two sequences, while the augmented repetition operator works on a sequence and an integer number.

Consider the following examples and pay attention to the result of calling the id() function:

Mutable sequences like lists support the += augmented assignment operator through the .__iadd__() method, which performs an in-place addition. This method mutates the underlying list, appending new values to its end.

Note: If the left operand is mutable, then x += y may not be completely equivalent to x = x + y . For example, if you do list_1 = list_1 + list_2 instead of list_1 += list_2 above, then you’ll create a new list instead of mutating the existing one. This may be important if other variables refer to the same list.

Immutable sequences, such as tuples and strings, don’t provide an .__iadd__() method. Therefore, augmented concatenations fall back to the .__add__() method, which doesn’t modify the sequence in place but returns a new sequence.

There’s another difference between mutable and immutable sequences when you use them in an augmented concatenation. Consider the following examples:

With mutable sequences, the data to be concatenated can come as a list, tuple, string, or any other iterable. In contrast, with immutable sequences, the data can only come as objects of the same type. You can concatenate tuples to tuples and strings to strings, for example.

Again, the augmented repetition operator works with a sequence on the left side of the operator and an integer on the right side. This integer value represents the number of repetitions to get in the resulting sequence:

When the *= operator operates on a mutable sequence, it falls back to the .__imul__() method, which performs the operation in place, modifying the underlying sequence. In contrast, if *= operates on an immutable sequence, then .__mul__() is called, returning a new sequence of the same type.

Note: Values of n less than 0 are treated as 0 , which returns an empty sequence of the same data type as the target sequence on the left side of the *= operand.

Note that a_list[0] is a_list[3] returns True . This is because the *= operator doesn’t make a copy of the repeated data. It only reflects the data. This behavior can be a source of issues when you use the operator with mutable values.

For example, say that you want to create a list of lists to represent a matrix, and you need to initialize the list with n empty lists, like in the following code:

In this example, you use the *= operator to populate matrix with three empty lists. Now check out what happens when you try to populate the first sublist in matrix :

The appended values are reflected in the three sublists. This happens because the *= operator doesn’t make copies of the data that you want to repeat. It only reflects the data. Therefore, every sublist in matrix points to the same object and memory address.

If you ever need to initialize a list with a bunch of empty sublists, then use a list comprehension :

This time, when you populate the first sublist of matrix , your changes aren’t propagated to the other sublists. This is because all the sublists are different objects that live in different memory addresses.

Bitwise operators also have their augmented versions. The logic behind them is similar to that of the math operators. The following table summarizes the augmented bitwise operators that Python provides:

Operator Operation Example Equivalent
Augmented bitwise AND ( )
Augmented bitwise OR ( )
Augmented bitwise XOR ( )
Augmented bitwise right shift
Augmented bitwise left shift

The augmented bitwise assignment operators perform the intended operation by taking the current value of the left operand as a starting point for the computation. Consider the following example, which uses the & and &= operators:

Programmers who work with high-level languages like Python rarely use bitwise operations in day-to-day coding. However, these types of operations can be useful in some situations.

For example, say that you’re implementing a Unix-style permission system for your users to access a given resource. In this case, you can use the characters "r" for reading, "w" for writing, and "x" for execution permissions, respectively. However, using bit-based permissions could be more memory efficient:

You can assign permissions to your users with the OR bitwise operator or the augmented OR bitwise operator. Finally, you can use the bitwise AND operator to check if a user has a certain permission, as you did in the final two examples.

You’ve learned a lot about augmented assignment operators and statements in this and the previous sections. These operators apply to math, concatenation, repetition, and bitwise operations. Now you’re ready to look at other assignment variants that you can use in your code or find in other developers’ code.

Other Assignment Variants

So far, you’ve learned that Python’s assignment statements and the assignment operator are present in many different scenarios and use cases. Those use cases include variable creation and initialization, parallel assignments, iterable unpacking, augmented assignments, and more.

In the following sections, you’ll learn about a few variants of assignment statements that can be useful in your future coding. You can also find these assignment variants in other developers’ code. So, you should be aware of them and know how they work in practice.

In short, you’ll learn about:

  • Annotated assignment statements with type hints
  • Assignment expressions with the walrus operator
  • Managed attribute assignments with properties and descriptors
  • Implicit assignments in Python

These topics will take you through several interesting and useful examples that showcase the power of Python’s assignment statements.

PEP 526 introduced a dedicated syntax for variable annotation back in Python 3.6 . The syntax consists of the variable name followed by a colon ( : ) and the variable type:

Even though these statements declare three variables with their corresponding data types, the variables aren’t actually created or initialized. So, for example, you can’t use any of these variables in an augmented assignment statement:

If you try to use one of the previously declared variables in an augmented assignment, then you get a NameError because the annotation syntax doesn’t define the variable. To actually define it, you need to use an assignment.

The good news is that you can use the variable annotation syntax in an assignment statement with the = operator:

The first statement in this example is what you can call an annotated assignment statement in Python. You may ask yourself why you should use type annotations in this type of assignment if everybody can see that counter holds an integer number. You’re right. In this example, the variable type is unambiguous.

However, imagine what would happen if you found a variable initialization like the following:

What would be the data type of each user in users ? If the initialization of users is far away from the definition of the User class, then there’s no quick way to answer this question. To clarify this ambiguity, you can provide the appropriate type hint for users :

Now you’re clearly communicating that users will hold a list of User instances. Using type hints in assignment statements that initialize variables to empty collection data types—such as lists, tuples, or dictionaries—allows you to provide more context about how your code works. This practice will make your code more explicit and less error-prone.

Up to this point, you’ve learned that regular assignment statements with the = operator don’t have a return value. They just create or update variables. Therefore, you can’t use a regular assignment to assign a value to a variable within the context of an expression.

Python 3.8 changed this by introducing a new type of assignment statement through PEP 572 . This new statement is known as an assignment expression or named expression .

Note: Expressions are a special type of statement in Python. Their distinguishing characteristic is that expressions always have a return value, which isn’t the case with all types of statements.

Unlike regular assignments, assignment expressions have a return value, which is why they’re called expressions in the first place. This return value is automatically assigned to a variable. To write an assignment expression, you must use the walrus operator ( := ), which was named for its resemblance to the eyes and tusks of a walrus lying on its side.

The general syntax of an assignment statement is as follows:

This expression looks like a regular assignment. However, instead of using the assignment operator ( = ), it uses the walrus operator ( := ). For the expression to work correctly, the enclosing parentheses are required in most use cases. However, there are certain situations in which these parentheses are superfluous. Either way, they won’t hurt you.

Assignment expressions come in handy when you want to reuse the result of an expression or part of an expression without using a dedicated assignment to grab this value beforehand.

Note: Assignment expressions with the walrus operator have several practical use cases. They also have a few restrictions. For example, they’re illegal in certain contexts, such as lambda functions, parallel assignments, and augmented assignments.

For a deep dive into this special type of assignment, check out The Walrus Operator: Python’s Assignment Expressions .

A particularly handy use case for assignment expressions is when you need to grab the result of an expression used in the context of a conditional statement. For example, say that you need to write a function to compute the mean of a sample of numeric values. Without the walrus operator, you could do something like this:

In this example, the sample size ( n ) is a value that you need to reuse in two different computations. First, you need to check whether the sample has data points or not. Then you need to use the sample size to compute the mean. To be able to reuse n , you wrote a dedicated assignment statement at the beginning of your function to grab the sample size.

You can avoid this extra step by combining it with the first use of the target value, len(sample) , using an assignment expression like the following:

The assignment expression introduced in the conditional computes the sample size and assigns it to n . This way, you guarantee that you have a reference to the sample size to use in further computations.

Because the assignment expression returns the sample size anyway, the conditional can check whether that size equals 0 or not and then take a certain course of action depending on the result of this check. The return statement computes the sample’s mean and sends the result back to the function caller.

Python provides a few tools that allow you to fine-tune the operations behind the assignment of attributes. The attributes that run implicit operations on assignments are commonly referred to as managed attributes .

Properties are the most commonly used tool for providing managed attributes in your classes. However, you can also use descriptors and, in some cases, the .__setitem__() special method.

To understand what fine-tuning the operation behind an assignment means, say that you need a Point class that only allows numeric values for its coordinates, x and y . To write this class, you must set up a validation mechanism to reject non-numeric values. You can use properties to attach the validation functionality on top of x and y .

Here’s how you can write your class:

In Point , you use properties for the .x and .y coordinates. Each property has a getter and a setter method . The getter method returns the attribute at hand. The setter method runs the input validation using a try … except block and the built-in float() function. Then the method assigns the result to the actual attribute.

Here’s how your class works in practice:

When you use a property-based attribute as the left operand in an assignment statement, Python automatically calls the property’s setter method, running any computation from it.

Because both .x and .y are properties, the input validation runs whenever you assign a value to either attribute. In the first example, the input values are valid numbers and the validation passes. In the final example, "one" isn’t a valid numeric value, so the validation fails.

If you look at your Point class, you’ll note that it follows a repetitive pattern, with the getter and setter methods looking quite similar. To avoid this repetition, you can use a descriptor instead of a property.

A descriptor is a class that implements the descriptor protocol , which consists of four special methods :

  • .__get__() runs when you access the attribute represented by the descriptor.
  • .__set__() runs when you use the attribute in an assignment statement.
  • .__delete__() runs when you use the attribute in a del statement.
  • .__set_name__() sets the attribute’s name, creating a name-aware attribute.

Here’s how your code may look if you use a descriptor to represent the coordinates of your Point class:

You’ve removed repetitive code by defining Coordinate as a descriptor that manages the input validation in a single place. Go ahead and run the following code to try out the new implementation of Point :

Great! The class works as expected. Thanks to the Coordinate descriptor, you now have a more concise and non-repetitive version of your original code.

Another way to fine-tune the operations behind an assignment statement is to provide a custom implementation of .__setitem__() in your class. You’ll use this method in classes representing mutable data collections, such as custom list-like or dictionary-like classes.

As an example, say that you need to create a dictionary-like class that stores its keys in lowercase letters:

In this example, you create a dictionary-like class by subclassing UserDict from collections . Your class implements a .__setitem__() method, which takes key and value as arguments. The method uses str.lower() to convert key into lowercase letters before storing it in the underlying dictionary.

Python implicitly calls .__setitem__() every time you use a key as the left operand in an assignment statement. This behavior allows you to tweak how you process the assignment of keys in your custom dictionary.

Implicit Assignments in Python

Python implicitly runs assignments in many different contexts. In most cases, these implicit assignments are part of the language syntax. In other cases, they support specific behaviors.

Whenever you complete an action in the following list, Python runs an implicit assignment for you:

  • Define or call a function
  • Define or instantiate a class
  • Use the current instance , self
  • Import modules and objects
  • Use a decorator
  • Use the control variable in a for loop or a comprehension
  • Use the as qualifier in with statements , imports, and try … except blocks
  • Access the _ special variable in an interactive session

Behind the scenes, Python performs an assignment in every one of the above situations. In the following subsections, you’ll take a tour of all these situations.

When you define a function, the def keyword implicitly assigns a function object to your function’s name. Here’s an example:

From this point on, the name greet refers to a function object that lives at a given memory address in your computer. You can call the function using its name and a pair of parentheses with appropriate arguments. This way, you can reuse greet() wherever you need it.

If you call your greet() function with fellow as an argument, then Python implicitly assigns the input argument value to the name parameter on the function’s definition. The parameter will hold a reference to the input arguments.

When you define a class with the class keyword, you’re assigning a specific name to a class object . You can later use this name to create instances of that class. Consider the following example:

In this example, the name User holds a reference to a class object, which was defined in __main__.User . Like with a function, when you call the class’s constructor with the appropriate arguments to create an instance, Python assigns the arguments to the parameters defined in the class initializer .

Another example of implicit assignments is the current instance of a class, which in Python is called self by convention. This name implicitly gets a reference to the current object whenever you instantiate a class. Thanks to this implicit assignment, you can access .name and .job from within the class without getting a NameError in your code.

Import statements are another variant of implicit assignments in Python. Through an import statement, you assign a name to a module object, class, function, or any other imported object. This name is then created in your current namespace so that you can access it later in your code:

In this example, you import the sys module object from the standard library and assign it to the sys name, which is now available in your namespace, as you can conclude from the second call to the built-in dir() function.

You also run an implicit assignment when you use a decorator in your code. The decorator syntax is just a shortcut for a formal assignment like the following:

Here, you call decorator() with a function object as an argument. This call will typically add functionality on top of the existing function, func() , and return a function object, which is then reassigned to the func name.

The decorator syntax is syntactic sugar for replacing the previous assignment, which you can now write as follows:

Even though this new code looks pretty different from the above assignment, the code implicitly runs the same steps.

Another situation in which Python automatically runs an implicit assignment is when you use a for loop or a comprehension. In both cases, you can have one or more control variables that you then use in the loop or comprehension body:

The memory address of control_variable changes on each iteration of the loop. This is because Python internally reassigns a new value from the loop iterable to the loop control variable on each cycle.

The same behavior appears in comprehensions:

In the end, comprehensions work like for loops but use a more concise syntax. This comprehension creates a new list of strings that mimic the output from the previous example.

The as keyword in with statements, except clauses, and import statements is another example of an implicit assignment in Python. This time, the assignment isn’t completely implicit because the as keyword provides an explicit way to define the target variable.

In a with statement, the target variable that follows the as keyword will hold a reference to the context manager that you’re working with. As an example, say that you have a hello.txt file with the following content:

You want to open this file and print each of its lines on your screen. In this case, you can use the with statement to open the file using the built-in open() function.

In the example below, you accomplish this. You also add some calls to print() that display information about the target variable defined by the as keyword:

This with statement uses the open() function to open hello.txt . The open() function is a context manager that returns a text file object represented by an io.TextIOWrapper instance.

Since you’ve defined a hello target variable with the as keyword, now that variable holds a reference to the file object itself. You confirm this by printing the object and its memory address. Finally, the for loop iterates over the lines and prints this content to the screen.

When it comes to using the as keyword in the context of an except clause, the target variable will contain an exception object if any exception occurs:

In this example, you run a division that raises a ZeroDivisionError . The as keyword assigns the raised exception to error . Note that when you print the exception object, you get only the message because exceptions have a custom .__str__() method that supports this behavior.

There’s a final detail to remember when using the as specifier in a try … except block like the one in the above example. Once you leave the except block, the target variable goes out of scope , and you can’t use it anymore.

Finally, Python’s import statements also support the as keyword. In this context, you can use as to import objects with a different name:

In these examples, you use the as keyword to import the numpy package with the np name and pandas with the name pd . If you call dir() , then you’ll realize that np and pd are now in your namespace. However, the numpy and pandas names are not.

Using the as keyword in your imports comes in handy when you want to use shorter names for your objects or when you need to use different objects that originally had the same name in your code. It’s also useful when you want to make your imported names non-public using a leading underscore, like in import sys as _sys .

The final implicit assignment that you’ll learn about in this tutorial only occurs when you’re using Python in an interactive session. Every time you run a statement that returns a value, the interpreter stores the result in a special variable denoted by a single underscore character ( _ ).

You can access this special variable as you’d access any other variable:

These examples cover several situations in which Python internally uses the _ variable. The first two examples evaluate expressions. Expressions always have a return value, which is automatically assigned to the _ variable every time.

When it comes to function calls, note that if your function returns a fruitful value, then _ will hold it. In contrast, if your function returns None , then the _ variable will remain untouched.

The next example consists of a regular assignment statement. As you already know, regular assignments don’t return any value, so the _ variable isn’t updated after these statements run. Finally, note that accessing a variable in an interactive session returns the value stored in the target variable. This value is then assigned to the _ variable.

Note that since _ is a regular variable, you can use it in other expressions:

In this example, you first create a list of values. Then you call len() to get the number of values in the list. Python automatically stores this value in the _ variable. Finally, you use _ to compute the mean of your list of values.

Now that you’ve learned about some of the implicit assignments that Python runs under the hood, it’s time to dig into a final assignment-related topic. In the following few sections, you’ll learn about some illegal and dangerous assignments that you should be aware of and avoid in your code.

Illegal and Dangerous Assignments in Python

In Python, you’ll find a few situations in which using assignments is either forbidden or dangerous. You must be aware of these special situations and try to avoid them in your code.

In the following sections, you’ll learn when using assignment statements isn’t allowed in Python. You’ll also learn about some situations in which using assignments should be avoided if you want to keep your code consistent and robust.

You can’t use Python keywords as variable names in assignment statements. This kind of assignment is explicitly forbidden. If you try to use a keyword as a variable name in an assignment, then you get a SyntaxError :

Whenever you try to use a keyword as the left operand in an assignment statement, you get a SyntaxError . Keywords are an intrinsic part of the language and can’t be overridden.

If you ever feel the need to name one of your variables using a Python keyword, then you can append an underscore to the name of your variable:

In this example, you’re using the desired name for your variables. Because you added a final underscore to the names, Python doesn’t recognize them as keywords, so it doesn’t raise an error.

Note: Even though adding an underscore at the end of a name is an officially recommended practice , it can be confusing sometimes. Therefore, try to find an alternative name or use a synonym whenever you find yourself using this convention.

For example, you can write something like this:

In this example, using the name booking_class for your variable is way clearer and more descriptive than using class_ .

You’ll also find that you can use only a few keywords as part of the right operand in an assignment statement. Those keywords will generally define simple statements that return a value or object. These include lambda , and , or , not , True , False , None , in , and is . You can also use the for keyword when it’s part of a comprehension and the if keyword when it’s used as part of a ternary operator .

In an assignment, you can never use a compound statement as the right operand. Compound statements are those that require an indented block, such as for and while loops, conditionals, with statements, try … except blocks, and class or function definitions.

Sometimes, you need to name variables, but the desired or ideal name is already taken and used as a built-in name. If this is your case, think harder and find another name. Don’t shadow the built-in.

Shadowing built-in names can cause hard-to-identify problems in your code. A common example of this issue is using list or dict to name user-defined variables. In this case, you override the corresponding built-in names, which won’t work as expected if you use them later in your code.

Consider the following example:

The exception in this example may sound surprising. How come you can’t use list() to build a list from a call to map() that returns a generator of square numbers?

By using the name list to identify your list of numbers, you shadowed the built-in list name. Now that name points to a list object rather than the built-in class. List objects aren’t callable, so your code no longer works.

In Python, you’ll have nothing that warns against using built-in, standard-library, or even relevant third-party names to identify your own variables. Therefore, you should keep an eye out for this practice. It can be a source of hard-to-debug errors.

In programming, a constant refers to a name associated with a value that never changes during a program’s execution. Unlike other programming languages, Python doesn’t have a dedicated syntax for defining constants. This fact implies that Python doesn’t have constants in the strict sense of the word.

Python only has variables. If you need a constant in Python, then you’ll have to define a variable and guarantee that it won’t change during your code’s execution. To do that, you must avoid using that variable as the left operand in an assignment statement.

To tell other Python programmers that a given variable should be treated as a constant, you must write your variable’s name in capital letters with underscores separating the words. This naming convention has been adopted by the Python community and is a recommendation that you’ll find in the Constants section of PEP 8 .

In the following examples, you define some constants in Python:

The problem with these constants is that they’re actually variables. Nothing prevents you from changing their value during your code’s execution. So, at any time, you can do something like the following:

These assignments modify the value of two of your original constants. Python doesn’t complain about these changes, which can cause issues later in your code. As a Python developer, you must guarantee that named constants in your code remain constant.

The only way to do that is never to use named constants in an assignment statement other than the constant definition.

You’ve learned a lot about Python’s assignment operators and how to use them for writing assignment statements . With this type of statement, you can create, initialize, and update variables according to your needs. Now you have the required skills to fully manage the creation and mutation of variables in your Python code.

In this tutorial, you’ve learned how to:

  • Write assignment statements using Python’s assignment operators
  • Work with augmented assignments in Python
  • Explore assignment variants, like assignment expression and managed attributes
  • Identify illegal and dangerous assignments in Python

Learning about the Python assignment operator and how to use it in assignment statements is a fundamental skill in Python. It empowers you to write reliable and effective Python code.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate best-practices python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python's Assignment Operator: Write Robust Assignments (Source Code)

🔒 No spam. We take your privacy seriously.

python assignment to array

NumPy: Get and set values in an array using various indexing

This article explains how to get and set values, such as individual elements or subarrays (e.g., rows or columns), in a NumPy array ( ndarray ) using various indexing.

  • Indexing on ndarrays — NumPy v1.26 Manual

Basics of selecting values in an ndarray

Specify with integers, specify with slices, specify with a list of boolean values: boolean indexing, specify with a list of integers: fancy indexing, combine different specification formats, assign new values to selected ranges, views and copies.

See the following articles for information on deleting, concatenating, and adding to ndarray .

  • NumPy: Delete rows/columns from an array with np.delete()
  • NumPy: Concatenate arrays with np.concatenate, np.stack, etc.
  • NumPy: Insert elements, rows, and columns into an array with np.insert()

The NumPy version used in this article is as follows. Note that functionality may vary between versions.

Individual elements or subarrays (such as rows or columns) in an ndarray can be selected by specifying their positions or ranges in each dimension with commas, as in [○, ○, ○, ...] . The trailing : can be omitted, making [○, ○, :, :] equivalent to [○, ○] .

For a 2D array, [i] selects the ith row, and [:, i] selects the ith column (indexes start from 0 ). More details will be provided later.

Positions in each dimension can be specified not only as integers but also in other formats such as lists or slices, allowing for the selection of any subarray.

Positions (indexes) are specified as integers ( int ).

Indexes start from 0 , and negative values can be used to specify positions from the end ( -1 represents the last). Specifying a non-existent position results in an error.

The same applies to multi-dimensional arrays. Positions are specified for each dimension.

You can omit the specification of later dimensions.

In a 2D array, [i] , equivalent to [i, :] , selects the ith row as a 1D array, and [:, i] selects the ith column.

Ranges can be selected with slices ( start:end:step ).

  • NumPy: Slicing ndarray

Example with a 1D array:

Example with a 2D array:

The trailing : can be omitted.

Using a slice i:i+1 selects a single row or column, preserving the array's dimensions, unlike selection with an integer ( int ), which reduces the dimensions.

  • NumPy: Get the number of dimensions, shape, and size of ndarray

Slices preserve the original array's dimensions, while integers reduce them. This difference can affect outcomes or cause errors in operations like concatenation, even with the same range selected.

Specifying a list or ndarray of Boolean values ( True or False ) matching the dimensions' sizes selects True positions, similar to masking.

An error occurs if the sizes do not match.

Rows or columns can be extracted using a slice : .

Note that specifying a list of Boolean values for multiple dimensions simultaneously does not yield the expected result. Using np.ix_() is necessary.

  • numpy.ix_ — NumPy v1.26 Manual

As with slices, selecting a range of width 1 (a single row or column) preserves the original array's number of dimensions.

A comparison on an ndarray yields a Boolean ndarray . Using this for indexing with [] selects True values, producing a flattened 1D array.

  • NumPy: Compare two arrays element-wise

Specify multiple conditions using & (AND), | (OR), and ~ (NOT) with parentheses () . Using and , or , not , or omitting parentheses results in an error.

  • How to fix "ValueError: The truth value ... is ambiguous" in NumPy, pandas

For methods of extracting rows or columns that meet certain conditions using Boolean indexing, refer to the following article.

  • NumPy: Extract or delete elements, rows, and columns that satisfy the conditions

It is also possible to select ranges with a list or ndarray of integers.

Order can be inverted or repeated, and using negative values is allowed. Essentially, it involves creating a new array by selecting specific positions from the original array.

As with Boolean indexing, specifying lists for multiple dimensions simultaneously does not yield the expected result. Using np.ix_() is necessary.

As in the 1D example, the order can be inverted or repeated, and negative values are also permissible.

When selecting with a list of one element, the original array's number of dimensions is preserved, in contrast to specifying with an integer.

Different formats can be used to specify each dimension.

A combination of a list of Boolean values and a list of integers requires the use of np.ix_() .

Note that np.ix_() can only accept 1D lists or arrays.

For example, when specifying multiple lists for arrays of three dimensions or more, np.ix_() is required. However, it cannot be combined with integers or slices in the same selection operation.

Integers can be specified as lists containing a single element. In this case, the resulting array retains the same number of dimensions as the original ndarray .

You can use range() to achieve similar functionality as slices. For example, to simulate slicing, retrieve the size of the target dimension using the shape attribute and pass it to range() as in range(a.shape[n])[::] .

  • How to use range() in Python

You can assign new values to selected ranges in an ndarray .

Specifying a scalar value on the right side assigns that value to all elements in the selected range on the left side.

Arrays can also be specified on the right side.

If the shape of the selected range on the left side matches that of the array on the right side, it is directly assigned. Non-contiguous locations pose no problem.

If the shape of the selected range on the left side does not match that of the array on the right side, it is assigned through broadcasting.

An error occurs if the shapes cannot be broadcast.

For more information on broadcasting, refer to the following article.

  • NumPy: Broadcasting rules and examples

The specification format used for each dimension when selecting subarrays determines whether a view or a copy of the original array is returned.

For example, using slices returns a view.

Whether two arrays refer to the same memory can be checked using np.shares_memory() .

  • NumPy: Views and copies of arrays

In the case of a view, changing the value in the selected subarray also changes the value in the original array, and vice versa.

Boolean indexing or fancy indexing returns a copy.

In this case, changing the value in the selected subarray does not affect the original array, and vice versa.

To create a copy of a subarray selected with a slice and process it separately from the original ndarray , use the copy() method.

When combining different specification formats, using Boolean or fancy indexing returns a copy.

Using integers and slices returns a view.

Related Categories

Related articles.

  • NumPy: Functions ignoring NaN (np.nansum, np.nanmean, etc.)
  • NumPy: Generate random numbers with np.random
  • NumPy: Ellipsis (...) for ndarray
  • List of NumPy articles
  • NumPy: arange() and linspace() to generate evenly spaced values
  • NumPy: Trigonometric functions (sin, cos, tan, arcsin, arccos, arctan)
  • NumPy: np.sign(), np.signbit(), np.copysign()
  • NumPy: Set the display format for ndarray
  • NumPy: Meaning of the axis parameter (0, 1, -1)
  • NumPy: Read and write CSV files (np.loadtxt, np.genfromtxt, np.savetxt)
  • OpenCV, NumPy: Rotate and flip image
  • NumPy: Set whether to print full or truncated ndarray
  • NumPy: Calculate cumulative sum and product (np.cumsum, np.cumprod)

How Arrays Work in Python – Array Methods Explained with Code Examples

David Fagbuyiro

In this tutorial, you'll learn what an array is in Python. You'll also learn some possible ways to add elements to an existing array.

In Python, there is no need to use a specific data type for arrays. You can simply use a list with all the attributes of an array.

If you want to create an array that includes both integers and floating-point numbers, you can use Python's array module.

What is an Array?

An array is a unique type of variable that has the capacity to store more than one value at once.

Let's say you have a list of objects like country names. You could store the countries in separate variables as follows:

But suppose you wanted to search through all of the countries to discover a certain one. What if you had 200 countries instead of only 3?

The alternative is to store all these values in an array.

Arrays are useful for storing and manipulating multiple values of the same data type. They act like a variable that can hold a collection of values, all of which are the same type. These values are stored together in bordering memory.

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.

The append() method is used to add elements to the end of a list. In this case, 'orange' is appended to the fruits list, resulting in the list containing four elements: 'apple', 'banana', 'cherry', and 'orange'.

Here's another example for you:

Let's create an array containing the names of cars:

You can use the append() method to add a new element to an existing list/array just as seen below.

The Clear() method

The clear() method removes all the elements from the list, just as the name implies.

Below is an example using the clear() method:

Based on the explanation of the clear() method above, the result of this expression will be [] empty because we have cleared the entire list.

The Copy() method

This function creates and returns an identical copy of the original list.

In the above example, the copy() method creates a new array called fruits_copy, which is a shallow copy of the fruits array. Modifying the fruits_copy array will not affect the original fruits array.

Here's another example using the copy() method:

The Count() method

This method returns the number of elements with the specified value.

The code above creates a list called fruits with four elements: 'apple', 'banana', 'cherry', and another 'banana'. The count() method is then used on the fruits list to count the number of occurrences of the element 'banana'. It returns the count, which in this case is 2, as 'banana' appears twice in the list.

Finally, the count value is printed to the console, resulting in the output: 2.

Here's another example of using the count() method:

Output of this would return int "2" as the result because "Lexus" appears twice in the cars list.

The Extend() method

With this method, you can add the elements of a list (or any iterable) to the end of the current list.

In the example above, the extend() method is used to add the elements from the additional_fruits list to the fruits array. The resulting array contains all the elements from both arrays.

Note that the extend() method modifies the original array in place and does not return a new array.

The index() method

This method returns the index of the first element with the specified value.

This code above creates a list of fruits containing 'apple', 'banana', and 'cherry'. It then finds the index position of 'banana' in the list and assigns it to the variable 'index'. Finally, it prints the value of 'index', which in this case would be 1.

The insert() method

This array method adds an element at the specified position.

From the code above, we have an array numbers with elements [1, 2, 3, 5, 6]. We want to insert the number 4 at index 3 (which is the fourth position in the array, as Python is 0-indexed). By calling insert(3, 4), we insert the element 4 at the specified index, and the existing elements are shifted to the right to make room for the new element. The resulting array is [1, 2, 3, 4, 5, 6].

The pop() method

This method removes the element at the specified position.

And here's the output:

This code above deletes the second element from the 'cars' array using the 'pop()' method and then prints the updated array.

Here's another example using the pop() method:

The code deletes the second element from the cars array using the pop() method and then prints the modified array. The resulting array will contain only the first and third elements: ['Lexus', 'Toyota'].

The remove() method

This method removes the first item with the specified value.

The code above creates a list called fruits with three elements: 'apple', 'banana', and 'cherry'. The remove() method is then used to remove the element 'banana' from the list.

After removing 'banana', the updated list is printed using the print() function. The output will be ['apple', 'cherry'] , as 'banana' is no longer present in the list.

Here's another example using the remove() method:

The remove() function may also be used to remove an element from an array, but it should be noted that it only removes the first instance of the specified value from a list.

The reverse() method

This method reverses the order of the list.

The code above creates a list called fruits with three elements: 'apple', 'banana', and 'cherry'. Then, the reverse() method is called on the fruits list which reverses the order of its elements. Finally, the reversed list is printed using the print() function, resulting in the output ['cherry', 'banana', 'apple']. This means that the original order of the fruits list has been reversed.

The sort() method

This method sorts the list, just as the name implies.

The code above creates a list called numbers with the elements [4, 2, 1, 3] . The sort() method is then called on the numbers list, which sorts the elements in ascending order. After sorting, the numbers list becomes [1, 2, 3, 4] . Finally, the sorted list is printed to the console using print(numbers) , which outputs [1, 2, 3, 4] .

the sort() method in Python sorts the elements of a list in ascending order by default. If you want to sort the list in descending order, you can pass the parameter reverse=True to the sort() method.

Here's an example of how to sort the numbers list in descending order:

By passing reverse=True as an argument to the sort() method, the list is sorted in descending order.

Hopefully, after reading this article, you should now have a basic understanding of what an array is in Python.

You should also know the basic Python array methods that you'll use to modify an array or a list and how to use them.

I am David Fagbuyiro, a Software engineer and a Technical writer passionate about helping the developers' community by sharing my knowledge through writing.

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

TechBeamers

Python Arrays

Python arrays are homogenous data structures. They are used to store multiple items but allow only the same type of data. They are available in Python by importing the array module.

Python Arrays – A Beginner Guide

List, a built-in type in Python, is also capable of storing multiple values. However, they are different from arrays because they are not bound to any specific type.

So, to summarize, arrays are not fundamental types, but lists are internal to Python. An array accepts values of one kind while lists are independent of the data type. To know more about lists, check out our tutorial on Python List .

However, in this tutorial, you’ll get to know how to create an array, add/update, index, remove, and slice.

What is an Array in Python?

An array is a container used to contain a fixed number of items. But, there is an exception that values should be of the same type. The following are two terms often used with arrays.

  • Array element – Every value in an array represents an element.
  • Array index – Every element has some position in the array known as the index.

Let’s now see how Python represents an array.

Array Illustration

The array is made up of multiple parts. And each section of the array is an element. We can access all the values by specifying the corresponding integer index.

The first element starts at index 0 and so on. At the 9th index, the 10th item would appear. Check the below graphical illustration.

Declare Array in Python

You have first to import the array module in your Python script. After that, declare the array variable as per the below syntax.

In the above statements, “array_var” is the name of the array variable. And we’ve used the array() function which takes two parameters. “TypeCode” is the type of array whereas “Initializers” are the values to set in the array.

The argument “TypeCode” can be any value from the below chart.

In the above diagram, we’ve listed down all possible type codes for Python and C Types. But we’ll only be using the Python Types “i” for integers and “d” for floats here in our examples.

Also, note that there is one Unicode type shown in the chart. Its support ended with Python version 3.3. So, it is best not to use it in your programs.

Let’s consider a simple case to create an array of 10 integers.

We first imported the array module and then used the Python range() function to produce ten integers. We’ve also printed the numbers that our array variable would hold. Here is the outcome of the above program.

In the next sections, we’ll cover all actions that can be performed using arrays.

Array Operations

Indexing an array.

We can use indices to retrieve elements of an array. See the below example:

Arrays have their first element stored at the zeroth index. Also, you can see that if we use the -ve index, then it gives us elements from the tail end.

The output is:

Slicing arrays

The slice operator “:” is commonly used to slice Python lists and strings. However, it does work for the arrays also. Let’s see with the help of examples.

When you execute the above script, it produces the following output:

The following two points, you should note down:

  • When you pass both the left and right operands to the slice operator, then they act as the indexes.
  • If you take one of them whether the left or right one, then it represents the no. of elements.

Add/Update arrays in Python

We can make changes to an array in different ways. Some of these are as follows:

  • Assignment operator to change or update an array
  • Append() method to add one element
  • Extend() method to add multiple items

We’ll now understand each of these approaches with the help of examples.

Let’s begin by using the assignment operator to update an existing array variable.

Now, we’ll apply the append() and extend() methods on a given array. These work the same for lists in Python. See the tutorial below.

Must Read- Difference Between List Append() and Extend()

This program yields the following:

The point to note is that both append() and extend() add elements to the end. The next tip is an interesting one. We can join two or more arrays using the “+” operator. If interested, learn about the different operators available in Python .

The above script shows the following result after execution:

Remove array elements

There are multiple ways that we can follow to remove elements from an array. Here are these:

  • Python del operator
  • Remove() method
  • Pop() method

Let’s first check how Python del works to delete array members.

The output is as follows:

Now, let’s try to utilize the remove() and pop() methods. The former removes the given value from the array whereas the latter deletes the item at a specified index.

After running this code, we get the below result:

Reverse arrays in Python

Last but not least is how we can reverse the elements of an array in Python. There can be many approaches to this. However, we’ll take the following two:

  • Slice operator in Python
  • Python List comprehension

Check out the below sample code to invert the element in a given array.

The above code produces the following output after running:

Now, we are mentioning a bonus method to reverse the array using the reversed() call. This function inverts the elements and returns a “list_reverseiterator” type object. However, if you want more info, read our in-depth tutorial on 7 ways to reverse a list in Python .

Here is the output of the above example.

More tutorials on Arrays in Python- Subarrays of an Array in Python Sort Array Values in Python

You have successfully wrapped up this tutorial. Now, you should be comfortable with using Python arrays. However, practice more with examples to gain confidence.

Lastly, our site needs your support to remain free. Share this post on social media ( Linkedin / Twitter ) if you gained some knowledge from this tutorial.

To learn Python from scratch to depth – Read this step-by-step Python tutorial .

Happy coding, TechBeamers.

You Might Also Like

Python selenium webdriver tutorial, python vs c++ comparison, python copy module to copy lists, python multiline string, how to install python packages with requirements.txt, leave a reply.

Your email address will not be published. Required fields are marked *

Popular Tutorials

Indexing on ndarrays #

Indexing routines

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. The examples work just as well when assigning to an array. See Assigning values to indexed arrays for specific examples and explanations on how assignments work.

Note that in Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN] ; the latter is just syntactic sugar for the former.

Basic indexing #

Single element indexing #.

Single element indexing works exactly like that for other standard Python sequences. It is 0-based, and accepts negative indices for indexing from the end of the array.

It is not necessary to separate each dimension’s index into its own set of square brackets.

Note that if one indexes a multidimensional array with fewer indices than dimensions, one gets a subdimensional array. For example:

That is, each index specified selects the array corresponding to the rest of the dimensions selected. In the above example, choosing 0 means that the remaining dimension of length 5 is being left unspecified, and that what is returned is an array of that dimensionality and size. It must be noted that the returned array is a view , i.e., it is not a copy of the original, but points to the same values in memory as does the original array. In this case, the 1-D array at the first position (0) is returned. So using a single index on the returned array, results in a single element being returned. That is:

So note that x[0, 2] == x[0][2] though the second case is more inefficient as a new temporary array is created after the first index that is subsequently indexed by 2.

NumPy uses C-order indexing. That means that the last index usually represents the most rapidly changing memory location, unlike Fortran or IDL, where the first index represents the most rapidly changing location in memory. This difference represents a great potential for confusion.

Slicing and striding #

Basic slicing extends Python’s basic concept of slicing to N dimensions. Basic slicing occurs when obj is a slice object (constructed by start:stop:step notation inside of brackets), an integer, or a tuple of slice objects and integers. Ellipsis and newaxis objects can be interspersed with these as well.

The simplest case of indexing with N integers returns an array scalar representing the corresponding item. As in Python, all indices are zero-based: for the i -th index \(n_i\) , the valid range is \(0 \le n_i < d_i\) where \(d_i\) is the i -th element of the shape of the array. Negative indices are interpreted as counting from the end of the array ( i.e. , if \(n_i < 0\) , it means \(n_i + d_i\) ).

All arrays generated by basic slicing are always views of the original array.

NumPy slicing creates a view instead of a copy as in the case of built-in Python sequences such as string, tuple and list. Care must be taken when extracting a small portion from a large array which becomes useless after the extraction, because the small portion extracted contains a reference to the large original array whose memory will not be released until all arrays derived from it are garbage-collected. In such cases an explicit copy() is recommended.

The standard rules of sequence slicing apply to basic slicing on a per-dimension basis (including using a step index). Some useful concepts to remember include:

The basic slice syntax is i:j:k where i is the starting index, j is the stopping index, and k is the step ( \(k\neq0\) ). This selects the m elements (in the corresponding dimension) with index values i , i + k , …, i + (m - 1) k where \(m = q + (r\neq0)\) and q and r are the quotient and remainder obtained by dividing j - i by k : j - i = q k + r , so that i + (m - 1) k < j . For example:

Negative i and j are interpreted as n + i and n + j where n is the number of elements in the corresponding dimension. Negative k makes stepping go towards smaller indices. From the above example:

Assume n is the number of elements in the dimension being sliced. Then, if i is not given it defaults to 0 for k > 0 and n - 1 for k < 0 . If j is not given it defaults to n for k > 0 and -n-1 for k < 0 . If k is not given it defaults to 1. Note that :: is the same as : and means select all indices along this axis. From the above example:

If the number of objects in the selection tuple is less than N , then : is assumed for any subsequent dimensions. For example:

An integer, i , returns the same values as i:i+1 except the dimensionality of the returned object is reduced by 1. In particular, a selection tuple with the p -th element an integer (and all other entries : ) returns the corresponding sub-array with dimension N - 1 . If N = 1 then the returned object is an array scalar. These objects are explained in Scalars .

If the selection tuple has all entries : except the p -th entry which is a slice object i:j:k , then the returned array has dimension N formed by stacking, along the p -th axis, the sub-arrays returned by integer indexing of elements i , i+k , …, i + (m - 1) k < j .

Basic slicing with more than one non- : entry in the slicing tuple, acts like repeated application of slicing using a single non- : entry, where the non- : entries are successively taken (with all other non- : entries replaced by : ). Thus, x[ind1, ..., ind2,:] acts like x[ind1][..., ind2, :] under basic slicing.

The above is not true for advanced indexing.

You may use slicing to set values in the array, but (unlike lists) you can never grow the array. The size of the value to be set in x[obj] = value must be (broadcastable to) the same shape as x[obj] .

A slicing tuple can always be constructed as obj and used in the x[obj] notation. Slice objects can be used in the construction in place of the [start:stop:step] notation. For example, x[1:10:5, ::-1] can also be implemented as obj = (slice(1, 10, 5), slice(None, None, -1)); x[obj] . This can be useful for constructing generic code that works on arrays of arbitrary dimensions. See Dealing with variable numbers of indices within programs for more information.

Dimensional indexing tools #

There are some tools to facilitate the easy matching of array shapes with expressions and in assignments.

Ellipsis expands to the number of : objects needed for the selection tuple to index all dimensions. In most cases, this means that the length of the expanded selection tuple is x.ndim . There may only be a single ellipsis present. From the above example:

This is equivalent to:

Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension. The added dimension is the position of the newaxis object in the selection tuple. newaxis is an alias for None , and None can be used in place of this with the same result. From the above example:

This can be handy to combine two arrays in a way that otherwise would require explicit reshaping operations. For example:

Advanced indexing #

Advanced indexing is triggered when the selection object, obj , is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). There are two types of advanced indexing: integer and Boolean.

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view ).

The definition of advanced indexing means that x[(1, 2, 3),] is fundamentally different than x[(1, 2, 3)] . The latter is equivalent to x[1, 2, 3] which will trigger basic selection while the former will trigger advanced indexing. Be sure to understand why this occurs.

Integer array indexing #

Integer array indexing allows selection of arbitrary items in the array based on their N -dimensional index. Each integer array represents a number of indices into that dimension.

Negative values are permitted in the index arrays and work as they do with single indices or slices:

If the index values are out of bounds then an IndexError is thrown:

When the index consists of as many integer arrays as dimensions of the array being indexed, the indexing is straightforward, but different from slicing.

Advanced indices always are broadcast and iterated as one :

Note that the resulting shape is identical to the (broadcast) indexing array shapes ind_1, ..., ind_N . If the indices cannot be broadcast to the same shape, an exception IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes... is raised.

Indexing with multidimensional index arrays tend to be more unusual uses, but they are permitted, and they are useful for some problems. We’ll start with the simplest multidimensional case:

In this case, if the index arrays have a matching shape, and there is an index array for each dimension of the array being indexed, the resultant array has the same shape as the index arrays, and the values correspond to the index set for each position in the index arrays. In this example, the first index value is 0 for both index arrays, and thus the first value of the resultant array is y[0, 0] . The next value is y[2, 1] , and the last is y[4, 2] .

If the index arrays do not have the same shape, there is an attempt to broadcast them to the same shape. If they cannot be broadcast to the same shape, an exception is raised:

The broadcasting mechanism permits index arrays to be combined with scalars for other indices. The effect is that the scalar value is used for all the corresponding values of the index arrays:

Jumping to the next level of complexity, it is possible to only partially index an array with index arrays. It takes a bit of thought to understand what happens in such cases. For example if we just use one index array with y:

It results in the construction of a new array where each value of the index array selects one row from the array being indexed and the resultant array has the resulting shape (number of index elements, size of row).

In general, the shape of the resultant array will be the concatenation of the shape of the index array (or the shape that all the index arrays were broadcast to) with the shape of any unused dimensions (those not indexed) in the array being indexed.

From each row, a specific element should be selected. The row index is just [0, 1, 2] and the column index specifies the element to choose for the corresponding row, here [0, 1, 0] . Using both together the task can be solved using advanced indexing:

To achieve a behaviour similar to the basic slicing above, broadcasting can be used. The function ix_ can help with this broadcasting. This is best understood with an example.

From a 4x3 array the corner elements should be selected using advanced indexing. Thus all elements for which the column is one of [0, 2] and the row is one of [0, 3] need to be selected. To use advanced indexing one needs to select all elements explicitly . Using the method explained previously one could write:

However, since the indexing arrays above just repeat themselves, broadcasting can be used (compare operations such as rows[:, np.newaxis] + columns ) to simplify this:

This broadcasting can also be achieved using the function ix_ :

Note that without the np.ix_ call, only the diagonal elements would be selected:

This difference is the most important thing to remember about indexing with multiple advanced indices.

A real-life example of where advanced indexing may be useful is for a color lookup table where we want to map the values of an image into RGB triples for display. The lookup table could have a shape (nlookup, 3). Indexing such an array with an image with shape (ny, nx) with dtype=np.uint8 (or any integer type so long as values are with the bounds of the lookup table) will result in an array of shape (ny, nx, 3) where a triple of RGB values is associated with each pixel location.

Boolean array indexing #

This advanced indexing occurs when obj is an array object of Boolean type, such as may be returned from comparison operators. A single boolean index array is practically identical to x[obj.nonzero()] where, as described above, obj.nonzero() returns a tuple (of length obj.ndim ) of integer index arrays showing the True elements of obj . However, it is faster when obj.shape == x.shape .

If obj.ndim == x.ndim , x[obj] returns a 1-dimensional array filled with the elements of x corresponding to the True values of obj . The search order will be row-major , C-style. An index error will be raised if the shape of obj does not match the corresponding dimensions of x , regardless of whether those values are True or False .

A common use case for this is filtering for desired element values. For example, one may wish to select all entries from an array which are not numpy.nan :

Or wish to add a constant to all negative elements:

In general if an index includes a Boolean array, the result will be identical to inserting obj.nonzero() into the same position and using the integer array indexing mechanism described above. x[ind_1, boolean_array, ind_2] is equivalent to x[(ind_1,) + boolean_array.nonzero() + (ind_2,)] .

If there is only one Boolean array and no integer indexing array present, this is straightforward. Care must only be taken to make sure that the boolean index has exactly as many dimensions as it is supposed to work with.

In general, when the boolean array has fewer dimensions than the array being indexed, this is equivalent to x[b, ...] , which means x is indexed by b followed by as many : as are needed to fill out the rank of x. Thus the shape of the result is one dimension containing the number of True elements of the boolean array, followed by the remaining dimensions of the array being indexed:

Here the 4th and 5th rows are selected from the indexed array and combined to make a 2-D array.

From an array, select all rows which sum up to less or equal two:

Combining multiple Boolean indexing arrays or a Boolean with an integer indexing array can best be understood with the obj.nonzero() analogy. The function ix_ also supports boolean arrays and will work without any surprises.

Use boolean indexing to select all rows adding up to an even number. At the same time columns 0 and 2 should be selected with an advanced integer index. Using the ix_ function this can be done with:

Without the np.ix_ call, only the diagonal elements would be selected.

Or without np.ix_ (compare the integer array examples):

Use a 2-D boolean array of shape (2, 3) with four True elements to select rows from a 3-D array of shape (2, 3, 5) results in a 2-D result of shape (4, 5):

Combining advanced and basic indexing #

When there is at least one slice ( : ), ellipsis ( ... ) or newaxis in the index (or the array has more dimensions than there are advanced indices), then the behaviour can be more complicated. It is like concatenating the indexing result for each advanced index element.

In the simplest case, there is only a single advanced index combined with a slice. For example:

In effect, the slice and index array operation are independent. The slice operation extracts columns with index 1 and 2, (i.e. the 2nd and 3rd columns), followed by the index array operation which extracts rows with index 0, 2 and 4 (i.e the first, third and fifth rows). This is equivalent to:

A single advanced index can, for example, replace a slice and the result array will be the same. However, it is a copy and may have a different memory layout. A slice is preferable when it is possible. For example:

The easiest way to understand a combination of multiple advanced indices may be to think in terms of the resulting shape. There are two parts to the indexing operation, the subspace defined by the basic indexing (excluding integers) and the subspace from the advanced indexing part. Two cases of index combination need to be distinguished:

The advanced indices are separated by a slice, Ellipsis or newaxis . For example x[arr1, :, arr2] .

The advanced indices are all next to each other. For example x[..., arr1, arr2, :] but not x[arr1, :, 1] since 1 is an advanced index in this regard.

In the first case, the dimensions resulting from the advanced indexing operation come first in the result array, and the subspace dimensions after that. In the second case, the dimensions from the advanced indexing operations are inserted into the result array at the same spot as they were in the initial array (the latter logic is what makes simple advanced indexing behave just like slicing).

Suppose x.shape is (10, 20, 30) and ind is a (2, 3, 4)-shaped indexing intp array, then result = x[..., ind, :] has shape (10, 2, 3, 4, 30) because the (20,)-shaped subspace has been replaced with a (2, 3, 4)-shaped broadcasted indexing subspace. If we let i, j, k loop over the (2, 3, 4)-shaped subspace then result[..., i, j, k, :] = x[..., ind[i, j, k], :] . This example produces the same result as x.take(ind, axis=-2) .

Let x.shape be (10, 20, 30, 40, 50) and suppose ind_1 and ind_2 can be broadcast to the shape (2, 3, 4). Then x[:, ind_1, ind_2] has shape (10, 2, 3, 4, 40, 50) because the (20, 30)-shaped subspace from X has been replaced with the (2, 3, 4) subspace from the indices. However, x[:, ind_1, :, ind_2] has shape (2, 3, 4, 10, 30, 50) because there is no unambiguous place to drop in the indexing subspace, thus it is tacked-on to the beginning. It is always possible to use .transpose() to move the subspace anywhere desired. Note that this example cannot be replicated using take .

Slicing can be combined with broadcasted boolean indices:

Field access #

Structured arrays

If the ndarray object is a structured array the fields of the array can be accessed by indexing the array with strings, dictionary-like.

Indexing x['field-name'] returns a new view to the array, which is of the same shape as x (except when the field is a sub-array) but of data type x.dtype['field-name'] and contains only the part of the data in the specified field. Also, record array scalars can be “indexed” this way.

Indexing into a structured array can also be done with a list of field names, e.g. x[['field-name1', 'field-name2']] . As of NumPy 1.16, this returns a view containing only those fields. In older versions of NumPy, it returned a copy. See the user guide section on Structured arrays for more information on multifield indexing.

If the accessed field is a sub-array, the dimensions of the sub-array are appended to the shape of the result. For example:

Flat iterator indexing #

x.flat returns an iterator that will iterate over the entire array (in C-contiguous style with the last index varying the fastest). This iterator object can also be indexed using basic slicing or advanced indexing as long as the selection object is not a tuple. This should be clear from the fact that x.flat is a 1-dimensional view. It can be used for integer indexing with 1-dimensional C-style-flat indices. The shape of any returned array is therefore the shape of the integer indexing object.

Assigning values to indexed arrays #

As mentioned, one can select a subset of an array to assign to using a single index, slices, and index and mask arrays. The value being assigned to the indexed array must be shape consistent (the same shape or broadcastable to the shape the index produces). For example, it is permitted to assign a constant to a slice:

or an array of the right size:

Note that assignments may result in changes if assigning higher types to lower types (like floats to ints) or even exceptions (assigning complex to floats or ints):

Unlike some of the references (such as array and mask indices) assignments are always made to the original data in the array (indeed, nothing else would make sense!). Note though, that some actions may not work as one may naively expect. This particular example is often surprising to people:

Where people expect that the 1st location will be incremented by 3. In fact, it will only be incremented by 1. The reason is that a new array is extracted from the original (as a temporary) containing the values at 1, 1, 3, 1, then the value 1 is added to the temporary, and then the temporary is assigned back to the original array. Thus the value of the array at x[1] + 1 is assigned to x[1] three times, rather than being incremented 3 times.

Dealing with variable numbers of indices within programs #

The indexing syntax is very powerful but limiting when dealing with a variable number of indices. For example, if you want to write a function that can handle arguments with various numbers of dimensions without having to write special case code for each number of possible dimensions, how can that be done? If one supplies to the index a tuple, the tuple will be interpreted as a list of indices. For example:

So one can use code to construct tuples of any number of indices and then use these within an index.

Slices can be specified within programs by using the slice() function in Python. For example:

Likewise, ellipsis can be specified by code by using the Ellipsis object:

For this reason, it is possible to use the output from the np.nonzero() function directly as an index since it always returns a tuple of index arrays.

Because of the special treatment of tuples, they are not automatically converted to an array as a list would be. As an example:

Detailed notes #

These are some detailed notes, which are not of importance for day to day indexing (in no particular order):

The native NumPy indexing type is intp and may differ from the default integer array type. intp is the smallest data type sufficient to safely index any array; for advanced indexing it may be faster than other types.

For advanced assignments, there is in general no guarantee for the iteration order. This means that if an element is set more than once, it is not possible to predict the final result.

An empty (tuple) index is a full scalar index into a zero-dimensional array. x[()] returns a scalar if x is zero-dimensional and a view otherwise. On the other hand, x[...] always returns a view.

If a zero-dimensional array is present in the index and it is a full integer index the result will be a scalar and not a zero-dimensional array. (Advanced indexing is not triggered.)

When an ellipsis ( ... ) is present but has no size (i.e. replaces zero : ) the result will still always be an array. A view if no advanced index is present, otherwise a copy.

The nonzero equivalence for Boolean arrays does not hold for zero dimensional boolean arrays.

When the result of an advanced indexing operation has no elements but an individual index is out of bounds, whether or not an IndexError is raised is undefined (e.g. x[[], [123]] with 123 being out of bounds).

When a casting error occurs during assignment (for example updating a numerical array using a sequence of strings), the array being assigned to may end up in an unpredictable partially updated state. However, if any other error (such as an out of bounds index) occurs, the array will remain unchanged.

The memory layout of an advanced indexing result is optimized for each indexing operation and no particular memory order can be assumed.

When using a subclass (especially one which manipulates its shape), the default ndarray.__setitem__ behaviour will call __getitem__ for basic indexing but not for advanced indexing. For such a subclass it may be preferable to call ndarray.__setitem__ with a base class ndarray view on the data. This must be done if the subclasses __getitem__ does not return views.

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 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:

Code C Type Python Type Min bytes
signed char int 1
unsigned char int 1
Py_UNICODE Unicode 2
signed short int 2
unsigned short int 2
signed int int 2
unsigned int int 2
signed long int 4
unsigned long int 4
float float 4
double float 8

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

  • Python Course
  • 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

Array Copying in Python

Let us see how to copy arrays in Python. There are 3 ways to copy arrays : 

  • Simply using the assignment operator.

Shallow Copy

Assigning the array.

We can create a copy of an array by using the assignment operator (=). 

Syntax :  

In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn’t. It only creates a new variable that shares the reference of the original object.

Output :  

We can see that both the arrays reference the same object. 

A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. In the case of shallow copy, a reference of the object is copied in another object. It means that any changes made to a copy of the object do reflect in the original object. We will be implementing shallow copy using the view() function.

Example :  

This time although the 2 arrays reference different objects, still on changing the value of one, the value of another also changes.

Deep copy is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In the case of deep copy, a copy of the object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object. We will be implementing deep copy using the copy() function.

This time the changes made in one array are not reflected in the other array.

Deep Copy Continued

If you are dealing with NumPy matrices, then numpy.copy() will give you a deep copy. However, if your matrix is simply a list of lists then consider the below two approaches in the task of rotating an image (represented as a list of a list) 90 degrees:

Please Login to comment...

Similar reads.

  • Python-array

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Python: Assigning values to 2D-array elements

I created a 2x2 2D-array of 0's as follows:

I want to change the second element of the first row to 1. I do this as follows:

Unfortunately, the second element of the second row also changes to 1.

Why does this happen?

Shoes's user avatar

  • 1 $\begingroup$ Have a look at the description/hove of tag python: Programming questions are off-topic here. (There are "no" arrays in Python: you show list s. Roughly, sequence * int means sequence repeated int times - while the result with immutable s is unsurprising, with object s it means referring to the same object in multiple places , with consequences as shown. (The object in question being a list with one nesting level less.)) $\endgroup$ –  greybeard Commented Nov 16, 2021 at 21:05
  • $\begingroup$ The two [0, 0] are "shallow copies", i.e. twice the same object. $\endgroup$ –  user16034 Commented Dec 12, 2022 at 9:25

This happens because of how you created the array.

I won't get into too much detail, but if you are familiar with the concept of "pointers", then an array is just a pointer - copying it will copy the pointer, so changing at one "clone" will change the other. Here you have copied your array twice.

To fix this, consider writing it in this form instead: [[0, 0] for _ in range(2)] which will create two brand-new lists and combine them - instead of copying the same one twice.

nir shahar's user avatar

  • $\begingroup$ Thank you so much! $\endgroup$ –  Shoes Commented Nov 16, 2021 at 11:16

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python or ask your own question .

  • Featured on Meta
  • Bringing clarity to status tag usage on meta sites
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Announcing a change to the data-dump process

Hot Network Questions

  • Base change in Chriss-Ginzburg
  • What connotation does "break out the checkbook" have?
  • What was the reason for not personifying God's spirit in NABRE's translation of John 14:17?
  • What is this houseplant with a red fleshy stem and thick waxy leaves?
  • Age is just a number!
  • Why would Space Colonies even want to secede?
  • Wiring 2 generators and utilizing a subpanel
  • Why would luck magic become obsolete in the modern era?
  • Why HIMEM was implemented as a DOS driver and not a TSR
  • What does "hypothecate" mean?
  • Word to classify what powers a god is associated with?
  • Do "Whenever X becomes the target of a spell" abilities get triggered by counterspell?
  • How did Jason Bourne know the garbage man isn't CIA?
  • Car LED circuit
  • Many and Many of - a subtle difference in meaning?
  • Painting Gold mettalic objects
  • Non-linear recurrence for rational sequences with generating function with radicals?
  • With 42 supernovae in 37 galaxies, how do we know SH0ES results is robust?
  • Making wobbly 6x4’ table stable
  • Does the First Amendment protect deliberately publicizing the incorrect date for an election?
  • Fisher claims Σ(x - λ)²/λ is chi-squared when x is Poisson – how is that?
  • How to handle stealth before combat starts?
  • A short story where a space pilot has a device that sends the ship back in time just before losing a space battle. He is duplicated by accident
  • How predictable are the voting records of members of the US legislative branch?

python assignment to array

Evaluate expressions in workflows and actions

You can evaluate expressions in workflows and actions.

In this article

About expressions.

You can use expressions to programmatically set environment variables in workflow files and access contexts. An expression can be any combination of literal values, references to a context, or functions. You can combine literals, context references, and functions using operators. For more information about contexts, see " Accessing contextual information about workflow runs ."

Expressions are commonly used with the conditional if keyword in a workflow file to determine whether a step should run. When an if conditional is true , the step will run.

You need to use specific syntax to tell GitHub to evaluate an expression rather than treat it as a string.

${{ <expression> }}

Note : The exception to this rule is when you are using expressions in an if clause, where, optionally, you can usually omit ${{ and }} . For more information about if conditionals, see " Workflow syntax for GitHub Actions ."

Warning: When creating workflows and actions, you should always consider whether your code might execute untrusted input from possible attackers. Certain contexts should be treated as untrusted input, as an attacker could insert their own malicious content. For more information, see " Security hardening for GitHub Actions ."

Example setting an environment variable

As part of an expression, you can use boolean , null , number , or string data types.

Data typeLiteral value
or
Any number format supported by JSON.
You don't need to enclose strings in and . However, if you do, you must use single quotes ( ) around the string. To use a literal single quote, escape the literal single quote using an additional single quote ( ). Wrapping with double quotes ( ) will throw an error.

Note that in conditionals, falsy values ( false , 0 , -0 , "" , '' , null ) are coerced to false and truthy ( true and other non-falsy values) are coerced to true .

Example of literals

OperatorDescription
Logical grouping
Index
Property de-reference
Not
Less than
Less than or equal
Greater than
Greater than or equal
Equal
Not equal
And
Or

GitHub ignores case when comparing strings.

  • steps.<step_id>.outputs.<output_name> evaluates as a string. You need to use specific syntax to tell GitHub to evaluate an expression rather than treat it as a string. For more information, see " Accessing contextual information about workflow runs ."
  • For numerical comparison, the fromJSON() function can be used to convert a string to a number. For more information on the fromJSON() function, see " fromJSON ."

GitHub performs loose equality comparisons.

If the types do not match, GitHub coerces the type to a number. GitHub casts data types to a number using these conversions:

TypeResult
Null
Boolean returns
returns
StringParsed from any legal JSON number format, otherwise .
Note: empty string returns .
Array
Object

When NaN is one of the operands of any relational comparison ( > , < , >= , <= ), the result is always false . For more information, see the " NaN Mozilla docs ."

Objects and arrays are only considered equal when they are the same instance.

GitHub offers ternary operator like behaviour that you can use in expressions. By using a ternary operator in this way, you can dynamically set the value of an environment variable based on a condition, without having to write separate if-else blocks for each possible option.

In this example, we're using a ternary operator to set the value of the MY_ENV_VAR environment variable based on whether the GitHub reference is set to refs/heads/main or not. If it is, the variable is set to value_for_main_branch . Otherwise, it is set to value_for_other_branches . It is important to note that the first value after the && must be truthy. Otherwise, the value after the || will always be returned.

GitHub offers a set of built-in functions that you can use in expressions. Some functions cast values to a string to perform comparisons. GitHub casts data types to a string using these conversions:

TypeResult
Null
Boolean or
NumberDecimal format, exponential for large numbers
ArrayArrays are not converted to a string
ObjectObjects are not converted to a string

contains( search, item )

Returns true if search contains item . If search is an array, this function returns true if the item is an element in the array. If search is a string, this function returns true if the item is a substring of search . This function is not case sensitive. Casts values to a string.

Example using a string

contains('Hello world', 'llo') returns true .

Example using an object filter

contains(github.event.issue.labels.*.name, 'bug') returns true if the issue related to the event has a label "bug".

For more information, see " Object filters ."

Example matching an array of strings

Instead of writing github.event_name == "push" || github.event_name == "pull_request" , you can use contains() with fromJSON() to check if an array of strings contains an item .

For example, contains(fromJSON('["push", "pull_request"]'), github.event_name) returns true if github.event_name is "push" or "pull_request".

startsWith( searchString, searchValue )

Returns true when searchString starts with searchValue . This function is not case sensitive. Casts values to a string.

Example of startsWith

startsWith('Hello world', 'He') returns true .

endsWith( searchString, searchValue )

Returns true if searchString ends with searchValue . This function is not case sensitive. Casts values to a string.

Example of endsWith

endsWith('Hello world', 'ld') returns true .

format( string, replaceValue0, replaceValue1, ..., replaceValueN)

Replaces values in the string , with the variable replaceValueN . Variables in the string are specified using the {N} syntax, where N is an integer. You must specify at least one replaceValue and string . There is no maximum for the number of variables ( replaceValueN ) you can use. Escape curly braces using double braces.

Example of format

Returns 'Hello Mona the Octocat'.

Example escaping braces

Returns '{Hello Mona the Octocat!}'.

join( array, optionalSeparator )

The value for array can be an array or a string. All values in array are concatenated into a string. If you provide optionalSeparator , it is inserted between the concatenated values. Otherwise, the default separator , is used. Casts values to a string.

Example of join

join(github.event.issue.labels.*.name, ', ') may return 'bug, help wanted'

toJSON(value)

Returns a pretty-print JSON representation of value . You can use this function to debug the information provided in contexts.

Example of toJSON

toJSON(job) might return { "status": "success" }

fromJSON(value)

Returns a JSON object or JSON data type for value . You can use this function to provide a JSON object as an evaluated expression or to convert any data type that can be represented in JSON or JavaScript, such as strings, booleans, null values, arrays, and objects.

Example returning a JSON object

This workflow sets a JSON matrix in one job, and passes it to the next job using an output and fromJSON .

Example returning a JSON data type

This workflow uses fromJSON to convert environment variables from a string to a Boolean or integer.

The workflow uses the fromJSON() function to convert the environment variable continue from a string to a boolean, allowing it to determine whether to continue-on-error or not. Similarly, it converts the time environment variable from a string to an integer, setting the timeout for the job in minutes.

hashFiles(path)

Returns a single hash for the set of files that matches the path pattern. You can provide a single path pattern or multiple path patterns separated by commas. The path is relative to the GITHUB_WORKSPACE directory and can only include files inside of the GITHUB_WORKSPACE . This function calculates an individual SHA-256 hash for each matched file, and then uses those hashes to calculate a final SHA-256 hash for the set of files. If the path pattern does not match any files, this returns an empty string. For more information about SHA-256, see " SHA-2 ."

You can use pattern matching characters to match file names. Pattern matching for hashFiles follows glob pattern matching and is case-insensitive on Windows. For more information about supported pattern matching characters, see the Patterns section in the @actions/glob documentation.

Example with a single pattern

Matches any package-lock.json file in the repository.

hashFiles('**/package-lock.json')

Example with multiple patterns

Creates a hash for any package-lock.json and Gemfile.lock files in the repository.

hashFiles('**/package-lock.json', '**/Gemfile.lock')

Status check functions

You can use the following status check functions as expressions in if conditionals. A default status check of success() is applied unless you include one of these functions. For more information about if conditionals, see " Workflow syntax for GitHub Actions " and " Metadata syntax for GitHub Actions ".

Returns true when all previous steps have succeeded.

Example of success

Causes the step to always execute, and returns true , even when canceled. The always expression is best used at the step level or on tasks that you expect to run even when a job is canceled. For example, you can use always to send logs even when a job is canceled.

Warning: Avoid using always for any task that could suffer from a critical failure, for example: getting sources, otherwise the workflow may hang until it times out. If you want to run a job or step regardless of its success or failure, use the recommended alternative: if: ${{ !cancelled() }}

Example of always

Returns true if the workflow was canceled.

Example of cancelled

Returns true when any previous step of a job fails. If you have a chain of dependent jobs, failure() returns true if any ancestor job fails.

Example of failure

Failure with conditions.

You can include extra conditions for a step to run after a failure, but you must still include failure() to override the default status check of success() that is automatically applied to if conditions that don't contain a status check function.

Example of failure with conditions

Object filters.

You can use the * syntax to apply a filter and select matching items in a collection.

For example, consider an array of objects named fruits .

The filter fruits.*.name returns the array [ "apple", "orange", "pear" ] .

You may also use the * syntax on an object. For example, suppose you have an object named vegetables .

The filter vegetables.*.ediblePortions could evaluate to:

Since objects don't preserve order, the order of the output cannot be guaranteed.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Python:How to assign a list or an array to an array element?

My code requires me to replace elements of an array of dimension 3x3 with a list or array of a certain dimension. How can I achieve that? When I write my code, it throws an error stating that:

In the code above I want to manipulate theta_g . In fact, I want to assign an array to each element of theta_g. How can I accomplish that? Desired Output: theta_g which is a matrix of dimension equal to that of c_g .

  • multidimensional-array

Amardeep Mishra's user avatar

  • can you mention your desired o/p ? –  Vikas Periyadath Commented Feb 7, 2018 at 7:07
  • what is Y in your code? and provide in detail traceback. –  Sociopath Commented Feb 7, 2018 at 7:09
  • Desired output is a matrix that has dimension equal to that of c_g. That is it is a matrix with dimenion 2x2 and the elements of this matrix are nothing but list or array. –  Amardeep Mishra Commented Feb 7, 2018 at 7:10
  • Akshay I have edited my code, Y is a single dimensional array. –  Amardeep Mishra Commented Feb 7, 2018 at 7:11
  • what is var? please give a full testable example. Also I'm still a little confused as to what your desired output is. You want an array, similar to that of c_g, which has what in each entry? –  Banana Commented Feb 7, 2018 at 7:13

2 Answers 2

I think you should just specify the type of the elements of the array as np.ndarray or list , like so:

Because you didn't really explain the logic of assignment, let me demonstrate in my own example, where I assign some arrays to a 2x2 array:

[[array([0, 0]) array([1, 2])] [array([1, 2]) array([10, 20])]]

Banana's user avatar

  • Yeah thanks a lot man! the first trick using np.ndarray worked! thanks once again! –  Amardeep Mishra Commented Feb 7, 2018 at 8:06
  • glad to be of help. –  Banana Commented Feb 7, 2018 at 8:10
  • Hi @Banana , also do you know any method in python to control the execution rate of a python loop? Lets say I want to run my loop at 100 herts or 10 milli seconds. How can I achieve that? –  Amardeep Mishra Commented Feb 7, 2018 at 8:28
  • @AmardeepMishra hey, yes you can use "import time" and then call "time.sleep(num_of_seconds)" to wait somewhere in the code. But if you have any further questions on that please search for it first and then open a new question, so others can also give their advice :) –  Banana Commented Feb 7, 2018 at 8:36

You can use np.stack .

Pratyush Singh's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python arrays list multidimensional-array or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Is the Ted-Ed Leprechaun's Magic Bag Unique?
  • Power line crossing data lines via the ground plane
  • What is a word/phrase that best describes a "blatant disregard or neglect" for something, but with the connotation of that they should have known?
  • A short story where a space pilot has a device that sends the ship back in time just before losing a space battle. He is duplicated by accident
  • Age is just a number!
  • What exactly is component based architecture and how do I get it to work?
  • Largest Eigenvalue Bound of Sum of Two Matrices
  • What is the airspeed record for a helicopter flying backwards?
  • How is 'or' used in the sentence 'alerting no one or killing no one but key targets'?
  • Can a Statute of Limitations claim be rejected by the court?
  • Why does editing '/etc/shells' file using 'sudo open' shows an error saying I don't own the file?
  • Using relative coordinates with \draw plot
  • Caulking Bathtub and Wall Surround to prevent water leak
  • Does the First Amendment protect deliberately publicizing the incorrect date for an election?
  • Non-linear recurrence for rational sequences with generating function with radicals?
  • What is the meaning of "Exit, pursued by a bear"?
  • Three 7-letter words, 21 unique letters, excludes either HM or QS
  • What does "hypothecate" mean?
  • What's wrong with my app authentication scheme?
  • How to cite a book if only its chapters have DOIs?
  • Why would luck magic become obsolete in the modern era?
  • A study on the speed of gravity
  • Is an invalid date considered the same as a NULL value?
  • Is it illegal to allow (verbally) someone to do action that may kill them?

python assignment to array

IMAGES

  1. How To Write An Array In Python

    python assignment to array

  2. Array Methods in Python

    python assignment to array

  3. (Tutorial) Python Arrays

    python assignment to array

  4. Everything about Arrays in Python

    python assignment to array

  5. Python: How to create an array in Python

    python assignment to array

  6. How to Create An Array in Python and other things you need to know

    python assignment to array

COMMENTS

  1. How to declare and add items to an array in Python

    To add elements to the list, use append. my_list.append(12) To extend the list to include the elements from another list use extend. my_list.extend([1,2,3,4]) my_list. --> [12,1,2,3,4] To remove an element from a list use remove. my_list.remove(2) Dictionaries represent a collection of key/value pairs also known as an associative array or a map.

  2. Assign values to array during loop

    I am currently learning Python (I have a strong background in Matlab). I would like to write a loop in Python, where the size of the array increases with every iteration (i.e., I can assign a newly calculated value to a different index of a variable). For the sake of this question, I am using a very simple loop to generate the vector t = [1 2 3 ...

  3. How To Add Elements to an Array in Python

    With the NumPy module, you can use the NumPy append() and insert() functions to add elements to an array. Appends the values or array to the end of a copy of arr. If the axis is not provided, then default is None, which means both arr and values are flattened before the append operation.

  4. 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])

  5. 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.

  6. 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.

  7. Introducing Numpy Arrays

    To define an array in Python, you could use the np.array function to convert a list. TRY IT! Create the following arrays: \(x = \begin{pmatrix} 1 & 4 & 3 \\ \end{pmatrix}\) ... You can reassign a value of an array by using array indexing and the assignment operator. You can reassign multiple elements to a single number using array indexing on ...

  8. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  9. NumPy: Get and set values in an array using various indexing

    This article explains how to get and set values, such as individual elements or subarrays (e.g., rows or columns), in a NumPy array ( ndarray) using various indexing. See the following articles for information on deleting, concatenating, and adding to ndarray. The NumPy version used in this article is as follows.

  10. 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:

  11. Python Arrays

    Let's begin by using the assignment operator to update an existing array variable. ... More tutorials on Arrays in Python-Subarrays of an Array in Python Sort Array Values in Python. You have successfully wrapped up this tutorial. Now, you should be comfortable with using Python arrays. However, practice more with examples to gain confidence.

  12. Indexing on ndarrays

    Indexing routines. 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.

  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. 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.

  15. Learn How To Use Arrays In Python With Example

    Accessing array elements : To access array elements, you need to specify the index values. Indexing starts at 0 and not from 1. Hence, the index number is always 1 less than the length of the array.

  16. 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))

  17. 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 ...

  18. Array Copying in Python

    There are 3 ways to copy arrays : Simply using the assignment operator. Shallow Copy. Deep Copy. Assigning the Array. We can create a copy of an array by using the assignment operator (=). Syntax : new_arr = old_ arr. In Python, Assignment statements do not copy objects, they create bindings between a target and an object.

  19. Python: Assigning values to 2D-array elements

    $\begingroup$ Have a look at the description/hove of tag python: Programming questions are off-topic here. (There are "no" arrays in Python: you show list s. Roughly, sequence * int means sequence repeated int times - while the result with immutable s is unsurprising, with object s it means referring to the same object in multiple places , with ...

  20. 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:

  21. Evaluate expressions in workflows and actions

    join( array, optionalSeparator ) The value for array can be an array or a string. All values in array are concatenated into a string. If you provide optionalSeparator, it is inserted between the concatenated values. Otherwise, the default separator , is used. Casts values to a string. Example of join

  22. Python:How to assign a list or an array to an array element?

    1. I think you should just specify the type of the elements of the array as np.ndarray or list, like so: theta_g=np.zeros((c_g.shape[0],c_g.shape[1]), dtype=np.ndarray) Because you didn't really explain the logic of assignment, let me demonstrate in my own example, where I assign some arrays to a 2x2 array: from itertools import product.