Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

How to dynamically assign properties to an object in TypeScript

type assignment in

Editor’s note: This article was updated on 6 October 2023, introducing solutions like type assertions and the Partial utility type to address the TypeScript error highlighted.

How To Dynamically Assign Properties To An Object In TypeScript

JavaScript is a dynamically typed language, meaning that a variable’s type is determined at runtime and by what it holds at the time of execution. This makes it flexible but also unreliable and prone to errors because a variable’s value might be unexpected.

TypeScript, on the other hand, is a statically typed version of JavaScript — unlike JavaScript, where a variable can change types randomly, TypeScript defines the type of a variable at its declaration or initialization.

Dynamic property assignment is the ability to add properties to an object only when they are needed. This can occur when an object has certain properties set in different parts of our code that are often conditional.

In this article, we will explore some ways to enjoy the dynamic benefits of JavaScript alongside the security of TypeScript’s typing in dynamic property assignment.

Consider the following example of TypeScript code:

This seemingly harmless piece of code throws a TypeScript error when dynamically assigning name to the organization object:

An Error Is Thrown When Dynamically Assigning A Property To An Object

See this example in the TypeScript Playground .

The source of confusion, perhaps rightly justified if you’re a TypeScript beginner, is: how could something that seems so simple be such a problem in TypeScript?

The TL;DR of it all is that if you can’t define the variable type at declaration time, you can use the Record utility type or an object index signature to solve this. But in this article, we’ll go through the problem itself and work toward a solution that should work in most cases.

The problem with dynamically assigning properties to objects

Generally speaking, TypeScript determines the type of a variable when it is declared. This determined type stays the same throughout your application. There are exceptions to this rule, such as when considering type narrowing or working with the any type, but otherwise, this is a general rule to remember.

In the earlier example, the organization object is declared as follows:

There is no explicit type assigned to this variable, so TypeScript infers a type of organization based on the declaration to be {} , i.e., the literal empty object.

If you add a type alias, you can explore the type of organization :

Exploring The Literal Object Type

See this in the TypeScript Playground .

When you then try to reference the name prop on this empty object literal:

You receive the following error:

There are many ways to solve the TypeScript error here. Let’s consider the following:

Solution 1: Explicitly type the object at declaration time

This is the easiest solution to reason through. At the time you declare the object, go ahead and type it, and assign all the relevant values:

This eliminates any surprises. You’re clearly stating what this object type is and rightly declaring all relevant properties when you create the object.

However, this is not always feasible if the object properties must be added dynamically, which is why we’re here.

Solution 2: Use an object index signature

Occasionally, the properties of the object truly need to be added at a time after they’ve been declared. In this case, you can use the object index signature, as follows:

When the organization variable is declared, you can explicitly type it to the following: {[key: string] : string} .

You might be used to object types having fixed property types:

However, you can also substitute name for a “variable type.” For example, if you want to define any string property on obj :

Note that the syntax is similar to how you’d use a variable object property in standard JavaScript:

The TypeScript equivalent is called an object index signature.

type assignment in

Over 200k developers use LogRocket to create better digital experiences

type assignment in

Moreover, note that you could type key with other primitives:

Solution 3: Use the Record Utility Type

The Record utility type allows you to constrict an object type whose properties are Keys and property values are Type . It has the following signature: Record<Keys, Type> .

In our example, Keys represents string and Type . The solution here is shown below:

Instead of using a type alias, you can also inline the type:

Using The Record Utility Type

Solution 4: Use the Map data type

A Map object is a fundamentally different data structure from an object , but for completeness, you could eliminate this problem if you were using Map .

Consider the starting example rewritten to use a Map object:

With Map objects, you’ll have no errors when dynamically assigning properties to the object:

Dark Background Typescript Playground Showing Map Object No Errors

This seems like a great solution at first, but the caveat is your Map object is weakly typed. You can access a nonexisting property and get no warnings at all:

See the TypeScript Playground .

This is unlike the standard object. By default, the initialized Map has the key and value types as any — i.e., new () => Map<any, any> . Consequently, the return type of the s variable will be any :

Dark Background Typescript Playground Showing Constant S With Type Any Indicated By Red Arrow

When using Map , at the very least, I strongly suggest passing some type information upon creation. For example:

s will still be undefined, but you won’t be surprised by its code usage. You’ll now receive the appropriate type for it:

Dark Background Typescript Playground Showing Properly Typed Map Value With Const S With Type String Undefined Indicated By Red Arrow

If you truly don’t know what the keys of the Map will be, you can go ahead and represent this at the type level:

And if you’re not sure what the keys or values are, be safe by representing this at the type level:

Solution 5: Consider an optional object property

This solution won’t always be possible, but if you know the name of the property to be dynamically assigned, you can optionally provide this when initializing the object as shown below:

If you don’t like the idea of using optional properties, you can be more explicit with your typing as shown below:

Solution 6: Leveraging type assertions

TypeScript type assertion is a mechanism that tells the compiler the variable’s type and overrides what it infers from the declaration or assignment. With this, we are telling the compiler to trust our understanding of the type because there will be no type verification.

We can perform a type assertion by either using the <> brackets or the as keyword. This is particularly helpful with the dynamic property assignment because it allows the properties we want for our object to be dynamically set because TypeScript won’t enforce them.

Let’s take a look at applying type assertions to our problem case:

Dark Background Typescript Playground Showing Dynamic Property Assignment Using Type Assertion

Note that with type assertions, the compiler is trusting that we will enforce the type we have asserted. This means if we don’t, for example, set a value for organization.name , it will throw an error at runtime that we will have to handle ourselves.

Solution 7: Use the Partial utility type

TypeScript provides several utility types that can be used to manipulate types. Some of these utility types are Partial , Omit , Required , and Pick .

For dynamic property assignments, we will focus specifically on the Partial utility type. This takes a defined type and makes all its properties optional. Thus, we can initialize our object with any combination of its properties, from none to all, as each one is optional:

In our example with the Partial utility type, we defined our organization object as the type partial Org , which means we can choose not to set a phoneNumber property:

Dark Background Typescript Playground Showing Dynamic Property Assignment Using Utility Type Partial

Grouping and comparing the options for adding properties in TypeScript

In this article, we explored the different options for setting properties dynamically in TypeScript. These options can be grouped together by their similarities.

Index/Key signatures

This group of options allows you to define the type of keys allowed without limiting what possible keys can exist. The options in this group include:

  • Using an object index signature
  • Using the Record utility type
  • Using the Map data type (with key/value typing)

With these, we can define that our object will take string indexes and decide what types to support as values, like String , Number , Boolean , or Any :

See in TypeScript Playground .

Pro: The main benefit of these methods is the ability to dynamically add properties to an object while still setting expectations for the potential types of keys and values.

Con: The main disadvantage of this way of defining objects is that you can’t predict what keys our objects will have and so some references may or may not be defined. An additional disadvantage is that if we decide to define our key signature with type Any , then the object becomes even more unpredictable.

Conditional/Optional properties

This set of object assignment methods shares a common feature: the definition of optional properties. This means that the range of possible properties are known but some may or may not be set. The options in this group include:

  • Using optional object properties
  • Using the Partial utility type
  • Using type assertions

See this example in the TypeScript Playground , or in the code block below:

Note: While these options mean that the possible keys are known and may not be set, TypeScript’s compiler won’t validate undefined states when using type assertions. This can lead to unhandled exceptions during runtime. For example, with optional properties and the Partial utility type, name has type string or undefined . Meanwhile, with type assertions, name has type string .

Pro: The advantage of this group of options is that all possible object keys and values are known.

Con: The disadvantage is that while the possible keys are known, we don’t know if those keys have been set and will have to handle the possibility that they are undefined.

Apart from primitives, the most common types you’ll have to deal with are likely object types. In cases where you need to build an object dynamically, take advantage of the Record utility type or use the object index signature to define the allowed properties on the object.

If you’d like to read more on this subject, feel free to check out my cheatsheet on the seven most-asked TypeScript questions on Stack Overflow, or tweet me any questions . Cheers!

LogRocket : Full visibility into your web and mobile apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

Try it for free .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • #typescript

Would you be interested in joining LogRocket's developer community?

Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

type assignment in

Stop guessing about your digital experience with LogRocket

Recent posts:.

This image features the iconic React logo—a blue atom-like symbol with a central dot and orbiting curves—superimposed on a background of a city skyline. The city appears to be shrouded in soft pink and purple hues, giving the image a modern, tech-focused atmosphere. This image symbolizex the use of React for building modular, scalable frontend architectures. React's component-based approach aligns with the principles of micro-frontends, where different parts of the user interface are independently developed and managed, similar to how microservices operate on the backend. The cityscape in the background represents the larger, complex web applications that can benefit from a structured, flexible frontend framework like React.

Practical guidance between vertical and horizontal micro-frontends

Micro-frontends, like microservices in backend development, divide frontend applications into modular, self-contained components that can be independently developed, tested, and […]

type assignment in

Tauri adoption guide: Overview, examples, and alternatives

Tauri is an excellent toolkit for building lightweight, secure, and cross-platform desktop applications. Learn more in this guide.

type assignment in

Developing modals using only CSS and the Popover API

The Dialog and Popover approach to modals requires less code and and fewer files than using JavaScript method, making it less error-prone.

type assignment in

Implementing Claude’s Artifacts feature for UI visualization

Use the Claude Artifacts feature to generate prototypes of user interfaces, saving you development time and giving you a way to easily visualize your plan.

type assignment in

3 Replies to "How to dynamically assign properties to an object in TypeScript"

I know this is explicitly for TypeScript, and I think type declarations should always be first. But in general, you can also use a Map object. If it’s really meant to by dynamic, might as well utilize the power of Map.

Great suggestion (updated the article). It’s worth mentioning the weak typing you get by default i.e., with respect to Typescript.

Hi, thanks for your valuable article please consider ‘keyof type’ in TypeScript, and add this useful solution if you are happy have nice time

Leave a Reply Cancel reply

Logo for University of Southern Queensland

Want to create or adapt books like this? Learn more about how Pressbooks supports open publishing practices.

Types of Assignments

Cristy Bartlett and Kate Derrington

Hand higghlighting notes on paper

Introduction

As discussed in the previous chapter, assignments are a common method of assessment at university. You may encounter many assignments over your years of study, yet some will look quite different from others. By recognising different types of assignments and understanding the purpose of the task, you can direct your writing skills effectively to meet task requirements. This chapter draws on the skills from the previous chapter, and extends the discussion, showing you where to aim with different types of assignments.

The chapter begins by exploring the popular essay assignment, with its two common categories, analytical and argumentative essays. It then examines assignments requiring case study responses , as often encountered in fields such as health or business. This is followed by a discussion of assignments seeking a report (such as a scientific report) and reflective writing assignments, common in nursing, education and human services. The chapter concludes with an examination of annotated bibliographies and literature reviews. The chapter also has a selection of templates and examples throughout to enhance your understanding and improve the efficacy of  your assignment writing skills.

Different Types of Written Assignments

At university, an essay is a common form of assessment. In the previous chapter Writing Assignments we discussed what was meant by showing academic writing in your assignments. It is important that you consider these aspects of structure, tone and language when writing an essay.

Components of an essay

Essays should use formal but reader friendly language and have a clear and logical structure. They must include research from credible academic sources such as peer reviewed journal articles and textbooks. This research should be referenced throughout your essay to support your ideas (See the chapter Working with Information ).

Diagram that allocates words of assignment

If you have never written an essay before, you may feel unsure about how to start.  Breaking your essay into sections and allocating words accordingly will make this process more manageable and will make planning the overall essay structure much easier.

  • An essay requires an introduction, body paragraphs and a conclusion.
  • Generally, an introduction and conclusion are approximately 10% each of the total word count.
  • The remaining words can then be divided into sections and a paragraph allowed for each area of content you need to cover.
  • Use your task and criteria sheet to decide what content needs to be in your plan

An effective essay introduction needs to inform your reader by doing four basic things:

Table 20.1 An effective essay

1 Engage their interest and provide a brief background of the topic.
2 Provide a thesis statement. This is the position or argument you will adopt. (Note a thesis statement is not always required. Check with your tutor).
3 Outline the structure of the essay.
4 Indicate any parameters or scope that will/will not be covered.

An effective essay body paragraph needs to:

1 State the topic sentence or main point of the paragraph. If you have a thesis statement, the topic sentence should relate to this.
2 Expand this main idea, define any terminology and explain concepts in more depth.
3 This information should be paraphrased and referenced from credible sources according to the appropriate referencing style of your course.
4 Demonstrate critical thinking by showing the relationship of the point you are making and the evidence you have included. This is where you introduce your “student voice”. Ask yourself the “So what?” question (as outlined in the critical thinking section) to add a discussion or interpretation of the how evidence you have included in your paragraph is relevant to your topic.
5 Conclude your idea and link to your next point.

An effective essay conclusion needs to:

1 Summarise or state the main points covered, using past tense.
2 Provide an overall conclusion that relates to the thesis statement or position you raised in your introduction.
3 Not add any new information.

Elements of essay in diagram

Common types of essays

You may be required to write different types of essays, depending on your study area and topic. Two of the most commonly used essays are analytical and argumentative .  The task analysis process discussed in the previous chapter Writing Assignments will help you determine the type of essay required. For example, if your assignment question uses task words such as analyse, examine, discuss, determine or explore, you would be writing an analytical essay . If your assignment question has task words such as argue, evaluate, justify or assess, you would be writing an argumentative essay . Despite the type of essay, your ability to analyse and think critically is important and common across genres.  

Analytical essays

Woman writing an essay

These essays usually provide some background description of the relevant theory, situation, problem, case, image, etcetera that is your topic. Being analytical requires you to look carefully at various components or sections of your topic in a methodical and logical way to create understanding.

The purpose of the analytical essay is to demonstrate your ability to examine the topic thoroughly. This requires you to go deeper than description by considering different sides of the situation, comparing and contrasting a variety of theories and the positives and negatives of the topic. Although in an analytical essay your position on the topic may be clear, it is not necessarily a requirement that you explicitly identify this with a thesis statement, as is the case with an argumentative essay. If you are unsure whether you are required to take a position, and provide a thesis statement, it is best to check with your tutor.

Argumentative essays

These essays require you to take a position on the assignment topic. This is expressed through your thesis statement in your introduction. You must then present and develop your arguments throughout the body of your assignment using logically structured paragraphs. Each of these paragraphs needs a topic sentence that relates to the thesis statement. In an argumentative essay, you must reach a conclusion based on the evidence you have presented.

Case Study Responses

Case studies are a common form of assignment in many study areas and students can underperform in this genre for a number of key reasons.

Students typically lose marks for not:

  • Relating their answer sufficiently to the case details
  • Applying critical thinking
  • Writing with clear structure
  • Using appropriate or sufficient sources
  • Using accurate referencing

When structuring your response to a case study, remember to refer to the case. Structure your paragraphs similarly to an essay paragraph structure but include examples and data from the case as additional evidence to support your points (see Figure 20.5 ). The colours in the sample paragraph below show the function of each component.

Diagram fo structure of case study

The Nursing and Midwifery Board of Australia (NMBA) Code of Conduct and Nursing Standards (2018) play a crucial role in determining the scope of practice for nurses and midwives. A key component discussed in the code is the provision of person-centred care and the formation of therapeutic relationships between nurses and patients (NMBA, 2018). This ensures patient safety and promotes health and wellbeing (NMBA, 2018). The standards also discuss the importance of partnership and shared decision-making in the delivery of care (NMBA, 2018, 4). Boyd and Dare (2014) argue that good communication skills are vital for building therapeutic relationships and trust between patients and care givers. This will help ensure the patient is treated with dignity and respect and improve their overall hospital experience. In the case, the therapeutic relationship with the client has been compromised in several ways. Firstly, the nurse did not conform adequately to the guidelines for seeking informed consent before performing the examination as outlined in principle 2.3 (NMBA, 2018). Although she explained the procedure, she failed to give the patient appropriate choices regarding her health care. 

Topic sentence | Explanations using paraphrased evidence including in-text references | Critical thinking (asks the so what? question to demonstrate your student voice). | Relating the theory back to the specifics of the case. The case becomes a source of examples as extra evidence to support the points you are making.

Reports are a common form of assessment at university and are also used widely in many professions. It is a common form of writing in business, government, scientific, and technical occupations.

Reports can take many different structures. A report is normally written to present information in a structured manner, which may include explaining laboratory experiments, technical information, or a business case.  Reports may be written for different audiences including clients, your manager, technical staff, or senior leadership within an organisation. The structure of reports can vary, and it is important to consider what format is required. The choice of structure will depend upon professional requirements and the ultimate aims of the report. Consider some of the options in the table below (see Table 20.2 ).

Table 20.2 Explanations of different types of reports

Executive or Business Reports Overall purpose is to convey structured information for business decision making.
Short form or Summary Reports Are abbreviated report structures designed to convey information in a focused short form manner.
Scientific Reports Are used for scientific documentation purposes and may detail the results of research or describe an experiment or a research problem.
Technical Reports Are used to communicate technical information for decision making, this may include discussing technical problems and solutions.
Evaluation Reports Present the results of or a proposal for an evaluation or assessment of a policy, program, process or service.

Reflective writing

Reflective flower

Reflective writing is a popular method of assessment at university. It is used to help you explore feelings, experiences, opinions, events or new information to gain a clearer and deeper understanding of your learning. A reflective writing task requires more than a description or summary.  It requires you to analyse a situation, problem or experience, consider what you may have learnt and evaluate how this may impact your thinking and actions in the future. This requires critical thinking, analysis, and usually the application of good quality research, to demonstrate your understanding or learning from a situation. Essentially, reflective practice is the process of looking back on past experiences and engaging with them in a thoughtful way and drawing conclusions to inform future experiences. The reflection skills you develop at university will be vital in the workplace to assist you to use feedback for growth and continuous improvement. There are numerous models of reflective writing and you should refer to your subject guidelines for your expected format. If there is no specific framework, a simple model to help frame your thinking is What? So what? Now what?   (Rolfe et al., 2001).

Diagram of bubbles that state what, now what, so what

Table 20.3 What? So What? Now What? Explained.

What? Describe the experience – who, what, why, when, where?
So what? What have you learnt from this? Why does it matter? What has been the impact on you? In what way? Why? You can include connections to coursework, current events, past experiences.
Now what? What are you going to do as a result of your experience? How will you apply what you have learnt in the future? Are there critical questions to further pursue? Make an action plan of what you will do next.

Gibb's reflective cycle of decription, feelings, evauation, analysis, action plan, cocnlusion

The Gibbs’ Reflective Cycle

The Gibbs’ Cycle of reflection encourages you to consider your feelings as part of the reflective process. There are six specific steps to work through. Following this model carefully and being clear of the requirements of each stage, will help you focus your thinking and reflect more deeply. This model is popular in Health.

The 4 R’s of reflective thinking

This model (Ryan and Ryan, 2013) was designed specifically for university students engaged in experiential learning.  Experiential learning includes any ‘real-world’ activities including practice led activities, placements and internships.  Experiential learning, and the use of reflective practice to heighten this learning, is common in Creative Arts, Health and Education.

Annotated Bibliography

What is it.

An annotated bibliography is an alphabetical list of appropriate sources (books, journals or websites) on a topic, accompanied by a brief summary, evaluation and sometimes an explanation or reflection on their usefulness or relevance to your topic. Its purpose is to teach you to research carefully, evaluate sources and systematically organise your notes. An annotated bibliography may be one part of a larger assessment item or a stand-alone assessment piece. Check your task guidelines for the number of sources you are required to annotate and the word limit for each entry.

How do I know what to include?

When choosing sources for your annotated bibliography it is important to determine:

  • The topic you are investigating and if there is a specific question to answer
  • The type of sources on which you need to focus
  • Whether they are reputable and of high quality

What do I say?

Important considerations include:

  • Is the work current?
  • Is the work relevant to your topic?
  • Is the author credible/reliable?
  • Is there any author bias?
  • The strength and limitations (this may include an evaluation of research methodology).

Annnotated bibliography example

Literature Reviews

It is easy to get confused by the terminology used for literature reviews. Some tasks may be described as a systematic literature review when actually the requirement is simpler; to review the literature on the topic but do it in a systematic way. There is a distinct difference (see Table 20.4 ). As a commencing undergraduate student, it is unlikely you would be expected to complete a systematic literature review as this is a complex and more advanced research task. It is important to check with your lecturer or tutor if you are unsure of the requirements.

Table 20.4 Comparison of Literature Reviews

A literature review A systematic literature review
A review which analyses and synthesises the literature on your research topic in a systemic (clear and logical) way. It may be organised:
• Conceptually
• Chronologically
• Methodologically
A much larger and more complicated research project which follows a clearly defined research protocol or process to remove any reviewer bias. Each step in the search process is documented to ensure it is able to be replicated, repeated or updated.

Generally, you are required to establish the main ideas that have been written on your chosen topic. You may also be expected to identify gaps in the research. A literature review does not summarise and evaluate each resource you find (this is what you would do in an annotated bibliography). You are expected to analyse and synthesise or organise common ideas from multiple texts into key themes which are relevant to your topic (see Figure 20.10 ). Use a table or a spreadsheet, if you know how, to organise the information you find. Record the full reference details of the sources as this will save you time later when compiling your reference list (see Table 20.5 ).

Table of themes

Overall, this chapter has provided an introduction to the types of assignments you can expect to complete at university, as well as outlined some tips and strategies with examples and templates for completing them. First, the chapter investigated essay assignments, including analytical and argumentative essays. It then examined case study assignments, followed by a discussion of the report format. Reflective writing , popular in nursing, education and human services, was also considered. Finally, the chapter briefly addressed annotated bibliographies and literature reviews. The chapter also has a selection of templates and examples throughout to enhance your understanding and improve the efficacy of your assignment writing skills.

  • Not all assignments at university are the same. Understanding the requirements of different types of assignments will assist in meeting the criteria more effectively.
  • There are many different types of assignments. Most will require an introduction, body paragraphs and a conclusion.
  • An essay should have a clear and logical structure and use formal but reader friendly language.
  • Breaking your assignment into manageable chunks makes it easier to approach.
  • Effective body paragraphs contain a topic sentence.
  • A case study structure is similar to an essay, but you must remember to provide examples from the case or scenario to demonstrate your points.
  • The type of report you may be required to write will depend on its purpose and audience. A report requires structured writing and uses headings.
  • Reflective writing is popular in many disciplines and is used to explore feelings, experiences, opinions or events to discover what learning or understanding has occurred. Reflective writing requires more than description. You need to be analytical, consider what has been learnt and evaluate the impact of this on future actions.
  • Annotated bibliographies teach you to research and evaluate sources and systematically organise your notes. They may be part of a larger assignment.
  • Literature reviews require you to look across the literature and analyse and synthesise the information you find into themes.

Gibbs, G. (1988). Learning by doing: A guide to teaching and learning methods. Further Education Unit, Oxford Brookes University, Oxford.

Rolfe, G., Freshwater, D., Jasper, M. (2001). Critical reflection in nursing and the helping professions: a user’s guide . Basingstoke: Palgrave Macmillan.

Ryan, M. & Ryan, M. (2013). Theorising a model for teaching and assessing reflective learning in higher education.  Higher Education Research & Development , 32(2), 244-257. doi: 10.1080/07294360.2012.661704

Academic Success Copyright © 2021 by Cristy Bartlett and Kate Derrington is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License , except where otherwise noted.

Share This Book

TypeScript: Mastering Type Assignment and Type Inference

TypeScript introduced static typing, enabling developers to specify the types of variables, function parameters, and return values.

typescript-type-assignment-and-type-inference

TypeScript, a superset of JavaScript, introduces static typing, enabling developers to specify the types of variables, function parameters, and return values. This capability significantly enhances code quality and developer productivity by catching errors early in the development process. Two fundamental concepts in TypeScript's type system are type assignment and type inference. Understanding these concepts is crucial for leveraging TypeScript's full potential to create robust and error-resistant applications.

Type Assignment

Type assignment in TypeScript is straightforward: it allows developers to explicitly specify the type of a variable, function parameter, or return value. This explicit typing helps catch type-related errors during compilation, long before the code is executed.

Syntax and Usage

Type assignment is done using a colon ( : ) followed by the type. Here are a few examples:

In these examples, userName is explicitly declared as a string , isLoggedIn as a boolean , and userAge as a number . The greet function expects a string parameter and is also expected to return a string .

Type Inference

Type inference allows TypeScript to automatically deduce the types of variables and expressions when they are not explicitly provided. This feature simplifies the code by reducing the verbosity of type annotations, without sacrificing the benefits of static typing.

How Type Inference Works

TypeScript's type inference comes into play in several scenarios, such as variable initialization and default function parameters. Here's an example:

In these cases, TypeScript infers the types based on the initial values. userId is inferred to be a number , isAdmin a boolean , and the multiply function's return type is inferred as number .

Best Practices for Type Assignment and Inference

While TypeScript's type inference is powerful, relying solely on inference can sometimes lead to less readable code, especially in complex scenarios. Here are some best practices:

  • Use explicit types for public API boundaries : This includes exported functions, classes, and interfaces. Explicit types improve documentation and make your code easier to understand for other developers.
  • Leverage type inference for local variables : For simple, internal code blocks, let TypeScript infer the types of local variables to reduce verbosity.
  • Prefer const over let for immutable values : This makes your intention clear and allows TypeScript to infer the type more accurately.

TypeScript's type assignment and type inference are two pillars that support writing clear, error-free code. By combining explicit type annotations with TypeScript's intelligent type inference, developers can enjoy the best of both worlds: the flexibility of JavaScript with the robustness of a statically-typed language. Whether you're a seasoned TypeScript developer or just starting out, mastering these concepts is key to unlocking the full power of TypeScript in your projects.

For those looking to dive deeper into TypeScript and explore its vast capabilities, PullTheCode offers a wealth of resources, tutorials, and best practices. From type assignment and inference to advanced types and utility types, PullTheCode is your go-to destination for elevating your TypeScript skills.

Own your own Software!

Join PullTheCode and start building your own SaaS in minutes on a platform you own!

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Type-testing operators and cast expressions - is , as , typeof and casts

  • 5 contributors

These operators and expressions perform type checking or type conversion. The is operator checks if the run-time type of an expression is compatible with a given type. The as operator explicitly converts an expression to a given type if its run-time type is compatible with that type. Cast expressions perform an explicit conversion to a target type. The typeof operator obtains the System.Type instance for a type.

is operator

The is operator checks if the run-time type of an expression result is compatible with a given type. The is operator also tests an expression result against a pattern.

The expression with the type-testing is operator has the following form

where E is an expression that returns a value and T is the name of a type or a type parameter. E can't be an anonymous method or a lambda expression.

The is operator returns true when an expression result is non-null and any of the following conditions are true:

The run-time type of an expression result is T .

The run-time type of an expression result derives from type T , implements interface T , or another implicit reference conversion exists from it to T .

The run-time type of an expression result is a nullable value type with the underlying type T and the Nullable<T>.HasValue is true .

A boxing or unboxing conversion exists from the run-time type of an expression result to type T .

The is operator doesn't consider user-defined conversions.

The following example demonstrates that the is operator returns true if the run-time type of an expression result derives from a given type, that is, there exists a reference conversion between types:

The next example shows that the is operator takes into account boxing and unboxing conversions but doesn't consider numeric conversions :

For information about C# conversions, see the Conversions chapter of the C# language specification .

Type testing with pattern matching

The is operator also tests an expression result against a pattern. The following example shows how to use a declaration pattern to check the run-time type of an expression:

For information about the supported patterns, see Patterns .

as operator

The as operator explicitly converts the result of an expression to a given reference or nullable value type. If the conversion isn't possible, the as operator returns null . Unlike a cast expression , the as operator never throws an exception.

The expression of the form

where E is an expression that returns a value and T is the name of a type or a type parameter, produces the same result as

except that E is only evaluated once.

The as operator considers only reference, nullable, boxing, and unboxing conversions. You can't use the as operator to perform a user-defined conversion. To do that, use a cast expression .

The following example demonstrates the usage of the as operator:

As the preceding example shows, you need to compare the result of the as expression with null to check if the conversion is successful. You can use the is operator both to test if the conversion succeeds and, if it succeeds, assign its result to a new variable.

Cast expression

A cast expression of the form (T)E performs an explicit conversion of the result of expression E to type T . If no explicit conversion exists from the type of E to type T , a compile-time error occurs. At run time, an explicit conversion might not succeed and a cast expression might throw an exception.

The following example demonstrates explicit numeric and reference conversions:

For information about supported explicit conversions, see the Explicit conversions section of the C# language specification . For information about how to define a custom explicit or implicit type conversion, see User-defined conversion operators .

Other usages of ()

You also use parentheses to call a method or invoke a delegate .

Other use of parentheses is to adjust the order in which to evaluate operations in an expression. For more information, see C# operators .

typeof operator

The typeof operator obtains the System.Type instance for a type. The argument to the typeof operator must be the name of a type or a type parameter, as the following example shows:

The argument mustn't be a type that requires metadata annotations. Examples include the following types:

  • string? (or any nullable reference type)

These types aren't directly represented in metadata. The types include attributes that describe the underlying type. In both cases, you can use the underlying type. Instead of dynamic , you can use object . Instead of string? , you can use string .

You can also use the typeof operator with unbound generic types. The name of an unbound generic type must contain the appropriate number of commas, which is one less than the number of type parameters. The following example shows the usage of the typeof operator with an unbound generic type:

An expression can't be an argument of the typeof operator. To get the System.Type instance for the run-time type of an expression result, use the Object.GetType method.

Type testing with the typeof operator

Use the typeof operator to check if the run-time type of the expression result exactly matches a given type. The following example demonstrates the difference between type checking done with the typeof operator and the is operator :

Operator overloadability

The is , as , and typeof operators can't be overloaded.

A user-defined type can't overload the () operator, but can define custom type conversions that can be performed by a cast expression. For more information, see User-defined conversion operators .

C# language specification

For more information, see the following sections of the C# language specification :

  • The is operator
  • The as operator
  • Cast expressions
  • The typeof operator
  • C# operators and expressions
  • How to safely cast by using pattern matching and the is and as operators
  • Generics in .NET

Additional resources

TypeScript tutorial

Typescript exercises, typescript simple types.

TypeScript supports some simple types (primitives) you may know.

There are three main primitives in JavaScript and TypeScript.

  • boolean - true or false values
  • number - whole numbers and floating point values
  • string - text values like "TypeScript Rocks"

There are also 2 less common primitives used in later versions of Javascript and TypeScript.

  • bigint - whole numbers and floating point values, but allows larger negative and positive numbers than the number type.
  • symbol are used to create a globally unique identifier.

Type Assignment

When creating a variable, there are two main ways TypeScript assigns a type:

In both examples below firstName is of type string

Explicit Type

Explicit - writing out the type:

Explicit type assignment are easier to read and more intentional.

Implicit Type

Implicit - TypeScript will "guess" the type, based on the assigned value:

Note: Having TypeScript "guess" the type of a value is called infer .

Implicit assignment forces TypeScript to infer the value.

Implicit type assignment are shorter, faster to type, and often used when developing and testing.

Get Certified!

Error in type assignment.

TypeScript will throw an error if data types do not match.

Implicit type assignment would have made firstName less noticeable as a string , but both will throw an error:

JavaScript will not throw an error for mismatched types.

Unable to Infer

TypeScript may not always properly infer what the type of a variable may be. In such cases, it will set the type to any which disables type checking.

This behavior can be disabled by enabling noImplicitAny as an option in a TypeScript's project tsconfig.json . That is a JSON config file for customizing how some of TypeScript behaves.

Note: you may see primitive types capitalized like Boolean .

boolean !== Boolean For this tutorial just know to use the lower-cased values, the upper-case ones are for very specific circumstances.

Test Yourself With Exercises

There are two main ways TypeScript assigns a type:

Start the Exercise

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.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: vscode: invalid const assignment causes type hints to fail #4545

@Arithmomaniac

Arithmomaniac commented Sep 26, 2024

If the declared type and the assigned type of a const are misaligned, then when the const is used elsewhere, the type hint says "(error)" instead of showing the declared type:

I would expect to see "const foobad1: { Bar : string }".

Drop this into VSCode and mouse over :

. of the bug.

@Arithmomaniac

No branches or pull requests

@Arithmomaniac

Was this page helpful?

Type Compatibility

Type compatibility in TypeScript is based on structural subtyping. Structural typing is a way of relating types based solely on their members. This is in contrast with nominal typing. Consider the following code:

In nominally-typed languages like C# or Java, the equivalent code would be an error because the Dog class does not explicitly describe itself as being an implementer of the Pet interface.

TypeScript’s structural type system was designed based on how JavaScript code is typically written. Because JavaScript widely uses anonymous objects like function expressions and object literals, it’s much more natural to represent the kinds of relationships found in JavaScript libraries with a structural type system instead of a nominal one.

A Note on Soundness

TypeScript’s type system allows certain operations that can’t be known at compile-time to be safe. When a type system has this property, it is said to not be “sound”. The places where TypeScript allows unsound behavior were carefully considered, and throughout this document we’ll explain where these happen and the motivating scenarios behind them.

Starting out

The basic rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x . For example consider the following code involving an interface named Pet which has a name property:

To check whether dog can be assigned to pet , the compiler checks each property of pet to find a corresponding compatible property in dog . In this case, dog must have a member called name that is a string. It does, so the assignment is allowed.

The same rule for assignment is used when checking function call arguments:

Note that dog has an extra owner property, but this does not create an error. Only members of the target type ( Pet in this case) are considered when checking for compatibility. This comparison process proceeds recursively, exploring the type of each member and sub-member.

Be aware, however, that object literals may only specify known properties . For example, because we have explicitly specified that dog is of type Pet , the following code is invalid:

Comparing two functions

While comparing primitive types and object types is relatively straightforward, the question of what kinds of functions should be considered compatible is a bit more involved. Let’s start with a basic example of two functions that differ only in their parameter lists:

To check if x is assignable to y , we first look at the parameter list. Each parameter in x must have a corresponding parameter in y with a compatible type. Note that the names of the parameters are not considered, only their types. In this case, every parameter of x has a corresponding compatible parameter in y , so the assignment is allowed.

The second assignment is an error, because y has a required second parameter that x does not have, so the assignment is disallowed.

You may be wondering why we allow ‘discarding’ parameters like in the example y = x . The reason for this assignment to be allowed is that ignoring extra function parameters is actually quite common in JavaScript. For example, Array#forEach provides three parameters to the callback function: the array element, its index, and the containing array. Nevertheless, it’s very useful to provide a callback that only uses the first parameter:

Now let’s look at how return types are treated, using two functions that differ only by their return type:

The type system enforces that the source function’s return type be a subtype of the target type’s return type.

Function Parameter Bivariance

When comparing the types of function parameters, assignment succeeds if either the source parameter is assignable to the target parameter, or vice versa. This is unsound because a caller might end up being given a function that takes a more specialized type, but invokes the function with a less specialized type. In practice, this sort of error is rare, and allowing this enables many common JavaScript patterns. A brief example:

You can have TypeScript raise errors when this happens via the compiler flag strictFunctionTypes .

Optional Parameters and Rest Parameters

When comparing functions for compatibility, optional and required parameters are interchangeable. Extra optional parameters of the source type are not an error, and optional parameters of the target type without corresponding parameters in the source type are not an error.

When a function has a rest parameter, it is treated as if it were an infinite series of optional parameters.

This is unsound from a type system perspective, but from a runtime point of view the idea of an optional parameter is generally not well-enforced since passing undefined in that position is equivalent for most functions.

The motivating example is the common pattern of a function that takes a callback and invokes it with some predictable (to the programmer) but unknown (to the type system) number of arguments:

Functions with overloads

When a function has overloads, each overload in the target type must be matched by a compatible signature on the source type. This ensures that the source function can be called in all the same cases as the target function.

Enums are compatible with numbers, and numbers are compatible with enums. Enum values from different enum types are considered incompatible. For example,

Classes work similarly to object literal types and interfaces with one exception: they have both a static and an instance type. When comparing two objects of a class type, only members of the instance are compared. Static members and constructors do not affect compatibility.

Private and protected members in classes

Private and protected members in a class affect their compatibility. When an instance of a class is checked for compatibility, if the target type contains a private member, then the source type must also contain a private member that originated from the same class. Likewise, the same applies for an instance with a protected member. This allows a class to be assignment compatible with its super class, but not with classes from a different inheritance hierarchy which otherwise have the same shape.

Because TypeScript is a structural type system, type parameters only affect the resulting type when consumed as part of the type of a member. For example,

In the above, x and y are compatible because their structures do not use the type argument in a differentiating way. Changing this example by adding a member to Empty<T> shows how this works:

In this way, a generic type that has its type arguments specified acts just like a non-generic type.

For generic types that do not have their type arguments specified, compatibility is checked by specifying any in place of all unspecified type arguments. The resulting types are then checked for compatibility, just as in the non-generic case.

For example,

Advanced Topics

Subtype vs assignment.

So far, we’ve used “compatible”, which is not a term defined in the language spec. In TypeScript, there are two kinds of compatibility: subtype and assignment. These differ only in that assignment extends subtype compatibility with rules to allow assignment to and from any , and to and from enum with corresponding numeric values.

Different places in the language use one of the two compatibility mechanisms, depending on the situation. For practical purposes, type compatibility is dictated by assignment compatibility, even in the cases of the implements and extends clauses.

any , unknown , object , void , undefined , null , and never assignability

The following table summarizes assignability between some abstract types. Rows indicate what each is assignable to, columns indicate what is assignable to them. A ” ✓ ” indicates a combination that is compatible only when strictNullChecks is off.

any unknown object void undefined null never
any →
unknown →
object →
void →
undefined →
null →
never →

Reiterating The Basics :

  • Everything is assignable to itself.
  • any and unknown are the same in terms of what is assignable to them, different in that unknown is not assignable to anything except any .
  • unknown and never are like inverses of each other. Everything is assignable to unknown , never is assignable to everything. Nothing is assignable to never , unknown is not assignable to anything (except any ).
  • void is not assignable to or from anything, with the following exceptions: any , unknown , never , undefined , and null (if strictNullChecks is off, see table for details).
  • When strictNullChecks is off, null and undefined are similar to never : assignable to most types, most types are not assignable to them. They are assignable to each other.
  • When strictNullChecks is on, null and undefined behave more like void : not assignable to or from anything, except for any , unknown , and void ( undefined is always assignable to void ).

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Ryan Cavanaugh  (51)

Last updated: Sep 27, 2024  

  • Utility Menu

University Logo

GA4 Tracking Code

Gen ed writes, writing across the disciplines at harvard college.

  • Types of Assignments

Gen Ed courses transcend disciplinary boundaries in a variety of ways, so the types of writing assignments that they include also often venture outside the traditional discipline-specific essays. You may encounter a wide variety of assignment types in Gen Ed, but most can be categorized into four general types: 

  • Traditional academic assignments include the short essays or research papers most commonly associated with college-level assignments. Generally speaking, these kinds of assignments are "expository" in nature, i.e., they ask you to engage with ideas through evidence-base argument, written in formal prose. The majority of essays in Expos courses fall into this category of writing assignment types.  
  • Less traditional academic assignments include elements of engagement in academia not normally encountered by undergraduates. 
  • Traditional non-academic assignments include types of written communication that students are likely to encounter in real world situations. 
  • Less traditional non-academic assignments are those that push the boundaries of typical ‘writing’ assignments and are likely to include some kind of creative or artistic component.

Examples and Resources

Traditional academic.

For most of us, these are the most familiar types of college-level writing assignments. While they are perhaps less common in Gen Ed than in departmental courses, there are still numerous examples we could examine.

Two illustrations of common types include: 

Example 1: Short Essay  Professor Michael Sandel asks the students in his Gen Ed course on Tech Ethics to write several short essays over the course of the semester in which they make an argument in response to the course readings. Because many students will never have written a philosophy-style paper, Professor Sandel offers students a number of resources—from a guide on writing in philosophy, to sample graded essays, to a list of logical fallacies—to keep in mind. 

Example 2: Research Paper In Who Lives, Who Dies, Who Cares?, a Gen Ed course co-taught by multiple global health faculty members, students write a 12–15 page research paper on a biosocial analysis of a global health topic of their choosing for the final assignment. The assignment is broken up into two parts: (1) a proposal with annotated bibliography and (2) the final paper itself. The prompt clearly outlines the key qualities and features of a successful paper, which is especially useful for students who have not yet written a research paper in the sciences. 

Less Traditional Academic

In Gen Ed, sometimes assignments ask students to engage in academic work that, while familiar to faculty, is beyond the scope of the typical undergraduate experience. 

Here are a couple of examples from Gen Ed courses: 

Example 1: Design a conference  For the final project in her Gen Ed course, Global Feminisms, Professor Durba Mitra asks her students to imagine a dream conference  in the style of the feminist conferences they studied in class. Students are asked to imagine conference panels and events, potential speakers or exhibitions, and advertising materials. While conferences are a normal occurrence for graduate students and professors, undergraduates are much less likely to be familiar with this part of academic life, and this kind of assignment might require more specific background and instructions as part of the prompt. 

Example 2: Curate a museum exhibit In his Gen Ed class, Pyramid Schemes, Professor Peter Der Manuelian's final project offers students the option of designing a virtual museum exhibit . While exhibit curation can be a part of the academic life of an anthropologist or archaeologist, it's not often found in introductory undergraduate courses. In addition to selecting objects and creating a virtual exhibit layout, students also wrote an annotated bibliography as well as an exhibit introduction for potential visitors. 

Traditional Non-academic

One of the goals of Gen Ed is to encourage students to engage with the world around them. Sometimes writing assignments in Gen Ed directly mirror types of writing that students are likely to encounter in real-world, non-academic settings after they graduate.

The following are several examples of such assignments: 

Example 1: Policy memo In Power and Identity in the Middle East, Professor Melani Cammett assigns students a group policy memo evaluating "a major initiative aimed at promoting democracy in the Middle East and North Africa (MENA)." The assignment prompt is actually structured as a memo, providing context for students who likely lack experience with the format. It also outlines the key characteristics of a good memo, and it provides extensive advice on the process—especially important when students are working in groups. 

Example 2: Letter In Loss, Professor Kathleen Coleman asks students to write a letter of condolence . The letter has an unusual audience: a mother elephant who lost her calf. Since students may not have encountered this type of writing before, Professor Coleman also provides students with advice on process, pointing to some course readings that might be a good place to start. She also suggests a list of outside resources to help students get into the mindframe of addressing an elephant. 

Example 3: Podcast  Podcasts are becoming increasingly popular in Gen Ed classes, as they are in the real world. Though they're ultimately audio file outputs, they usually require writing and preparing a script ahead of time. For example, in Music from Earth, Professor Alex Rehding asks students to create a podcast in which they make an argument about a song studied in class. He usefully breaks up the assignments into two parts: (1) researching the song and preparing a script and (2) recording and making sonic choices about the presentation, offering students the opportunity to get feedback on the first part before moving onto the second. 

Less Traditional Non-academic

These are the types of assignments that perhaps are less obviously "writing" assignments. They usually involve an artistic or otherwise creative component, but they also often include some kind of written introduction or artist statement related to the work.

The following are several examples from recently offered Gen Ed courses: 

Example 1: Movie Professor Peter Der Manuelian offers students in his class, Pyramid Schemes, several options for the final project, one of which entails creating a 5–8 minute  iMovie making an argument about one of the themes of the course. Because relatively few students have prior experience making films, the teaching staff provide students with a written guide to making an iMovie as well as ample opportunities for tech support. In addition to preparing a script as part of the production, students also submit both an annotated bibliography and an artist’s statement. 

Example 2: Calligram In his course, Understanding Islam and Contemporary Muslim Societies, Professor Ali Asani asks students to browse through a provided list of resources about calligrams, which are an important traditional Islamic art form. Then they are required to "choose a concept or symbol associated with God in the Islamic tradition and attempt to represent it through a calligraphic design using the word Allah," in any medium they wish. Students also write a short explanation to accompany the design itself. 

Example 3: Soundscape In Music from Earth, Professor Alex Rehding has students create a soundscape . The soundscape is an audio file which involves layering sounds from different sources to create a single piece responding to an assigned question (e.g. "What sounds are characteristic of your current geographical region?"). Early on, as part of the development of the soundscape, students submit an artist's statement that explains the plan for the soundscape, the significance of the sounds, and the intention of the work. 

  • DIY Guides for Analytical Writing Assignments

For Students

  • Unpacking the Elements of Writing Prompts
  • Receiving Feedback

Assignment Decoder

cppreference.com

Assignment operators.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
General
(C++11)
(C++20)
(C++26)
(C++11)
(C++11)
-expression
-expression
-expression
(C++11)
(C++11)
(C++17)
(C++20)
    

Assignment operators modify the value of the object.

Operator name  Syntax  Prototype examples (for class T)
Inside class definition Outside class definition
simple assignment Yes T& T::operator =(const T2& b);
addition assignment Yes T& T::operator +=(const T2& b); T& operator +=(T& a, const T2& b);
subtraction assignment Yes T& T::operator -=(const T2& b); T& operator -=(T& a, const T2& b);
multiplication assignment Yes T& T::operator *=(const T2& b); T& operator *=(T& a, const T2& b);
division assignment Yes T& T::operator /=(const T2& b); T& operator /=(T& a, const T2& b);
remainder assignment Yes T& T::operator %=(const T2& b); T& operator %=(T& a, const T2& b);
bitwise AND assignment Yes T& T::operator &=(const T2& b); T& operator &=(T& a, const T2& b);
bitwise OR assignment Yes T& T::operator |=(const T2& b); T& operator |=(T& a, const T2& b);
bitwise XOR assignment Yes T& T::operator ^=(const T2& b); T& operator ^=(T& a, const T2& b);
bitwise left shift assignment Yes T& T::operator <<=(const T2& b); T& operator <<=(T& a, const T2& b);
bitwise right shift assignment Yes T& T::operator >>=(const T2& b); T& operator >>=(T& a, const T2& b);

this, and most also return *this so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void). can be any type including .
Definitions Assignment operator syntax Built-in simple assignment operator Assignment from an expression Assignment from a non-expression initializer clause Built-in compound assignment operator Example Defect reports See also

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is performed in a special member function, described in .

(since C++11)

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

target-expr new-value (1)
target-expr op new-value (2)
target-expr - the expression to be assigned to
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
new-value - the expression (until C++11) (since C++11) to assign to the target
  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

If new-value is not an expression, the assignment expression will never match an overloaded compound assignment operator.

(since C++11)

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

If the type of target-expr is volatile-qualified, the assignment is deprecated, unless the (possibly parenthesized) assignment expression is a or an .

(since C++20)

new-value is only allowed not to be an expression in following situations:

is of a , and new-value is empty or has only one element. In this case, given an invented variable t declared and initialized as T t = new-value , the meaning of x = new-value  is x = t. is of class type. In this case, new-value is passed as the argument to the assignment operator function selected by .   <double> z; z = {1, 2}; // meaning z.operator=({1, 2}) z += {1, 2}; // meaning z.operator+=({1, 2})   int a, b; a = b = {1}; // meaning a = b = 1; a = {1} = b; // syntax error
(since C++11)

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

& operator=(T*&, T*);
volatile & operator=(T*volatile &, T*);

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

operator=(T&, T);

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

operator=(A1&, A2);

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

operator*=(A1&, A2);
operator/=(A1&, A2);
operator+=(A1&, A2);
operator-=(A1&, A2);

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

operator%=(I1&, I2);
operator<<=(I1&, I2);
operator>>=(I1&, I2);
operator&=(I1&, I2);
operator^=(I1&, I2);
operator|=(I1&, I2);

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

& operator+=(T*&, );
& operator-=(T*&, );
volatile & operator+=(T*volatile &, );
volatile & operator-=(T*volatile &, );

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++11 for assignments to class type objects, the right operand
could be an initializer list only when the assignment
is defined by a user-defined assignment operator
removed user-defined
assignment constraint
C++11 E1 = {E2} was equivalent to E1 = T(E2)
( is the type of ), this introduced a C-style cast
it is equivalent
to E1 = T{E2}
C++20 compound assignment operators for volatile
-qualified types were inconsistently deprecated
none of them
is deprecated
C++11 an assignment from a non-expression initializer clause
to a scalar value would perform direct-list-initialization
performs copy-list-
initialization instead
C++20 bitwise compound assignment operators for volatile types
were deprecated while being useful for some platforms
they are not
deprecated

[ edit ] See also

Operator precedence

Operator overloading

Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b
a <=> b

a[...]
*a
&a
a->b
a.b
a->*b
a.*b

function call
a(...)
comma
a, b
conditional
a ? b : c
Special operators

converts one type to another related type
converts within inheritance hierarchies
adds or removes -qualifiers
converts type to unrelated type
converts one type to another by a mix of , , and
creates objects with dynamic storage duration
destructs objects previously created by the new expression and releases obtained memory area
queries the size of a type
queries the size of a (since C++11)
queries the type information of a type
checks if an expression can throw an exception (since C++11)
queries alignment requirements of a type (since C++11)

for Assignment operators
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 January 2024, at 23:41.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Logo

  • Turnitin Guides
  • Student hub
  • Submitting to Turnitin
  • Turnitin website
  • File requirements for student submission

If an assignment is set to  allow any file type , Turnitin will accept any file that:

  • is less than 100MB
  • is less than 800 pages

If an assignment is set to  allow only files that Turnitin can check for similarity , Turnitin will only accept files that can generate Similarity Reports. This includes:

  • files less than 100MB,
  • files with a minimum of 20 words
  • file less than 800 pages
  • Microsoft Word (DOC and DOCX)
  • Corel WordPerfect
  • Adobe PostScript
  • Plain text (TXT)
  • Rich Text Format (RTF)
  • Portable Document Format (PDF)
  • OpenOffice (ODT)
  • Hangul (HWP and HWPX)
  • Powerpoint (PPTX)

Google Docs via Google Drive

If you are using an unsupported word processor, you may need to save your plain text file as .txt or .rtf in order to upload to Turnitin.

If submitting with Google Drive, third-party cookies must be allowed in your browser, otherwise, any attempts to sign into Google to upload from Google Drive will fail. Note that Google Drive functionality is not supported in IE8 or below. Do not upload Google Doc (.gdoc) files directly as the file does not store the document, but contains a reference to it online, in Google Docs.

Turnitin will not accept PDF image files, forms, or portfolios, files that do not contain highlightable text (e.g. a scanned file - usually an image), documents containing multiple files or files created with software other than Adobe Acrobat. To determine if a document contains actual text, copy and paste a section or all of the text into a plain-text editor such as Microsoft Notepad or Apple TextEdit. If no text is copied over, the selection is not actual text.

Microsoft PowerPoint (.pptx, .ppsx, and .pps)

It is possible to submit PowerPoint files through Turnitin.com, Turnitinuk.com, LTI integrations, Moodle Plagiarism Plugin, Moodle Direct V2, and D2L V2. Turnitin converts the PowerPoint slide deck into a static PDF, leaving all text and images in their original format but leaving out features such as presenter notes, embedded video, and animations. Text with visual effects is not supported, and it is recommended that any visual effects such as shadows and 3D be removed prior to submitting to Turnitin.

The  .PPT  extension does not work with integrations. Use  .PPTX  instead.

Microsoft Excel (.xls and .xlsx)

The version of the file that can be viewed in the Document Viewer will look the same as it would if the Excel file had been saved as a PDF and submitted to Turnitin. We highly recommend that users pay attention to the image preview provided in the single file submission to verify that the file is presented in an acceptable manner. Users can adjust the way the file looks by editing the page setup and print area settings for the file prior to saving it and submitting it to Turnitin.

File types not checked for similarity

Turnitin will not accept the following to generate Similarity Reports:

  • Password protected files
  • Microsoft Works (.wps) files
  • Microsoft Word 2007 macros-enabled .docm files
  • OpenOffice Text (.odt) files created and downloaded from Google Docs online
  • Document (.doc) files created using OpenOffice, as they are not 100% Microsoft Word equivalent
  • Apple Pages
  • Spreadsheets created outside of Microsoft Excel (e.g., .ods)
  • Text with visual effects

Articles in this section

  • Submitting to an essay assignment
  • Uploading a file via direct submission
  • Trouble submitting your paper?
  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Assignment Operators in Programming

Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improving readability.

Table of Content

What are Assignment Operators?

  • Types of Assignment Operators
  • Assignment Operators in C
  • Assignment Operators in C++
  • Assignment Operators in Java
  • Assignment Operators in Python
  • Assignment Operators in C#
  • Assignment Operators in JavaScript
  • Application of Assignment Operators

Assignment operators are used in programming to  assign values  to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign ( = ), which assigns the value on the right side of the operator to the variable on the left side.

Types of Assignment Operators:

  • Simple Assignment Operator ( = )
  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )

Below is a table summarizing common assignment operators along with their symbols, description, and examples:

OperatorDescriptionExamples
= (Assignment)Assigns the value on the right to the variable on the left.  assigns the value 10 to the variable x.
+= (Addition Assignment)Adds the value on the right to the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
-= (Subtraction Assignment)Subtracts the value on the right from the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
*= (Multiplication Assignment)Multiplies the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
/= (Division Assignment)Divides the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
%= (Modulo Assignment)Calculates the modulo of the current value of the variable on the left and the value on the right, then assigns the result to the variable.  is equivalent to 

Assignment Operators in C:

Here are the implementation of Assignment Operator in C language:

Assignment Operators in C++:

Here are the implementation of Assignment Operator in C++ language:

Assignment Operators in Java:

Here are the implementation of Assignment Operator in java language:

Assignment Operators in Python:

Here are the implementation of Assignment Operator in python language:

Assignment Operators in C#:

Here are the implementation of Assignment Operator in C# language:

Assignment Operators in Javascript:

Here are the implementation of Assignment Operator in javascript language:

Application of Assignment Operators:

  • Variable Initialization : Setting initial values to variables during declaration.
  • Mathematical Operations : Combining arithmetic operations with assignment to update variable values.
  • Loop Control : Updating loop variables to control loop iterations.
  • Conditional Statements : Assigning different values based on conditions in conditional statements.
  • Function Return Values : Storing the return values of functions in variables.
  • Data Manipulation : Assigning values received from user input or retrieved from databases to variables.

Conclusion:

In conclusion, assignment operators in programming are essential tools for assigning values to variables and performing operations in a concise and efficient manner. They allow programmers to manipulate data and control the flow of their programs effectively. Understanding and using assignment operators correctly is fundamental to writing clear, efficient, and maintainable code in various programming languages.

Similar Reads

  • Programming

Please Login to comment...

  • Top Language Learning Apps in 2024
  • Top 20 Free VPN for iPhone in 2024: October Top Picks
  • How to Underline in Discord
  • How to Block Someone on Discord
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Related Tutorials:

  • The Walrus Operator: Python's Assignment Expressions
  • Operators and Expressions in Python
  • The Python return Statement: Usage and Best Practices
  • Python's Counter: The Pythonic Way to Count Objects
  • Numbers in 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.

type assignment in

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Remember language

Assignment (=)

The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:

  • Initializers of var , let , and const declarations
  • Default values of destructuring
  • Default parameters
  • Initializers of class fields

All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Simple assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators in the JS guide
  • Destructuring assignment

Java, A Beginner's Guide, 5th Edition, 5th Edition by Herbert Schildt

Get full access to Java, A Beginner's Guide, 5th Edition, 5th Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Type Conversion in Assignments

In programming, it is common to assign one type of variable to another. For example, you might want to assign an int value to a float variable, as shown here:

Image

When compatible types are mixed in an assignment, the value of the right side is automatically converted to the type of the left side. Thus, in the preceding fragment, the value in i is converted into a float and then assigned to f . However, because of Java’s strict type checking, not all types are compatible, and thus, not all type conversions are implicitly allowed. For example, boolean and int are not compatible.

When one type of data is assigned to another ...

Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

type assignment in

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

MyPy - "Incompatible types in assignment (expression has type None, variable has type ...)"

I've got the following function, which given a string of the form 'a-02/b-03/foobarbaz_c-04' , will extract the digits after a , b and c . The issue is that, for my use case, the input strings may not contain c , such that there will be no digits to extract.

Here's the code:

The issue I have is that, despite trying to make it clear that the last return argument is an Optional[int] , I can't get my linter to stop complaining about the variable c.

I get a warning at the line c = None that says:

Incompatible types in assignment (expression has type None, variable has type int)

How can I solve the issue?

  • python-typing

InSync's user avatar

4 Answers 4

If you don't annotate a variable, mypy will infer its type based on the very first assignment it sees.

So in this case, the line c = int(_info.group(1)) appears first, so mypy decides that the type must be int . It then subsequently complains when it sees c = None .

One way of working around this limitation is to just forward-declare the variable with the expected type. If you are using Python 3.6+ and can use variable annotations, you can do so like this:

Or perhaps more concisely, like this:

If you need to support older versions of Python, you can annotate the type using the comment-based syntax, like so:

rje's suggestion of doing:

...is also a reasonable one.

user2357112's user avatar

Aside from the nice approach given by this answer , I came across another way to get mypy to ignore the line by adding comment like the following:

This seems to ignore the type for the current line, but does not effect the type inference for the other areas where the variable is used.

alper's user avatar

  • 9 Don’t know why this was downvoted, it’s the best answer in my opinion: because mypy is a type annotation program, it’s not supposed to cause you to restructure your code (which all the other answers do). Thanks :-) –  Louis Maddox Commented Jul 9, 2021 at 22:31
  • I'm downvoting because this breaks type inference - mypy will treat c as having type int instead of type Optional[int] , and will treat all int operations as valid on c , even though c could be None . –  user2357112 Commented Nov 2, 2021 at 16:59
  • I agree with Louis here, for now this is the best solution. This honestly seems like a shortcoming of MyPy. Just because it is incapable of updating its inferred type, doesn't mean that we should refactor to something less readable/intuitive. Thank you! –  Zach Commented Nov 3, 2021 at 8:46

You should return either a tuple a,b,c or a tuple a,b without including c. This way you do not need to assign a value of None to c at all.

rje's user avatar

  • But that's the reason why I defined the return type to have an Optional[int] . Is there really no way around it? –  Daniel Commented Oct 15, 2018 at 18:53
  • Thanks for the update. That's unfortunately suboptimal in that it doesn't allow me to easily unpack the results when I use the function. That's why I wanted a tuple of int, int, Optional[int]. –  Daniel Commented Oct 15, 2018 at 18:57
  • Hmm. Did you try declaring c as an optional int, e.g. c: Optional[int] = None ? –  rje Commented Oct 15, 2018 at 19:01

try with | notation

Ryabchenko Alexander's user avatar

  • int | None and Optional[int] are the equivalent, and making this change won't affect the mypy's logic on c inside the function. –  joanis Commented May 6 at 12:51

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 python-typing mypy or ask your own question .

  • The Overflow Blog
  • Masked self-attention: How LLMs learn relationships between tokens
  • Deedy Das: from coding at Meta, to search at Google, to investing with Anthropic
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Feedback Requested: How do you use the tagged questions page?

Hot Network Questions

  • Did Classical Latin authors ever incorrectly utilize an Ablative of Location for nouns that utilize the Locative Case?
  • How do you measure exactly 31 minutes by burning the ropes?
  • How can I make a 2D FTL-lane map on a galaxy-wide scale?
  • How to do automated content publishing post deployment in XMCloud?
  • Does copying files from one drive to another also copy previously deleted data from the drive one?
  • A military space Saga with a woman who is a brilliant tactician and strategist
  • Easily unload gravel from pickup truck
  • Estimating an upper bound of hyperbolicity constants in Gromov-hyperbolic groups
  • God the Father punished the Son as sin-bearer: how does that prove God’s righteousness?
  • In John 3:16, what is the significance of Jesus' distinction between the terms 'world' and 'everyone who believes' within the context?
  • Are logic and mathematics the only fields in which certainty (proof) can be obtained?
  • What "Texas and federal law"s is SpaceX "in violation of"?
  • Code editor-script console missing
  • How to format units inside math environment?
  • Choosing MCU for motor control
  • Find all tuples with prescribed ordering
  • In-line function command different whether it is followed by a dot or not
  • What is the ideal time for reaching the airport for check-in?
  • How to Organise/Present Built Worlds?
  • What book is this proof from?
  • What is the average result of rolling Xd6 twice and taking the higher of the two sums?
  • On a glassed landmass, how long would it take for plants to grow?
  • Can I redeem myself with a better research paper if my thesis sucks?
  • What happens if parents refuse to name their newborn child?

type assignment in

COMMENTS

  1. How to dynamically assign properties to an object in TypeScript

    Learn how to use TypeScript features like object index signature, Record utility type, and Map data type to avoid errors when adding properties to an object dynamically. Compare different solutions and see examples in the TypeScript Playground.

  2. javascript

    The trick is helping Typescript type the object you are creating. My suggestion would be to assert the type of the property type, so that Typescript knows that the string assignment is actually a string literal. Example

  3. Types of Assignments

    Learn how to recognise and write different types of assignments at university, such as essays, case studies, reports, reflective writing and annotated bibliographies. This chapter provides definitions, examples, templates and tips for each assignment type.

  4. TypeScript: Mastering Type Assignment and Type Inference

    Type Assignment. Type assignment in TypeScript is straightforward: it allows developers to explicitly specify the type of a variable, function parameter, or return value. This explicit typing helps catch type-related errors during compilation, long before the code is executed. Syntax and Usage. Type assignment is done using a colon (:) followed ...

  5. TypeScript: Documentation

    Learn how TypeScript infers types from values in various contexts, such as variables, parameters, functions, and arrays. See examples of best common type, contextual typing, and union types.

  6. Different Forms of Assignment Statements in Python

    Learn how to use different forms of assignment statements in Python, such as basic, tuple, list, sequence, extended sequence, multiple-target and augmented assignment. See syntax, output and code examples for each form.

  7. Type-testing operators and cast expressions

    In this article. These operators and expressions perform type checking or type conversion. The is operator checks if the run-time type of an expression is compatible with a given type. The as operator explicitly converts an expression to a given type if its run-time type is compatible with that type. Cast expressions perform an explicit conversion to a target type.

  8. TypeScript: Documentation

    Learn how to use conditional types to describe the relation between the types of inputs and outputs in TypeScript. See examples of conditional types with generics, constraints, inferring, and distributive conditional types.

  9. TypeScript Simple Types

    Learn how to use primitive types (boolean, number, string, bigint, symbol) in TypeScript. See examples of explicit and implicit type assignment, error handling, and ...

  10. Assignment

    Learn what an assignment is, how it evolved over time, and what types of assignments are common in education. Find examples and templates for essays, research papers, case studies, lab reports, presentations, and creative projects.

  11. [Bug]: vscode: invalid const assignment causes type hints to fail

    If the declared type and the assigned type of a const are misaligned, then when the const is used elsewhere, the type hint says "(error)" instead of showing the declared type: I would expect to see "const foobad1: { Bar : string }". Reproduction. Drop this into VSCode and mouse over foobad1:

  12. Documentation

    Learn how TypeScript's structural type system compares types based on their members, not their names. See examples of assignment, function call, and parameter compatibility.

  13. Types of Assignments

    Learn about the four general types of writing assignments in Gen Ed courses: traditional academic, less traditional academic, traditional non-academic, and less traditional non-academic. See examples and resources for each type and how to approach them.

  14. Assignment operators

    For all other compound assignment operators, the type of target-expr must be an arithmetic type. In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

  15. File requirements for student submission

    If an assignment is set to allow any file type, Turnitin will accept any file that:. is less than 100MB; is less than 800 pages; If an assignment is set to allow only files that Turnitin can check for similarity, Turnitin will only accept files that can generate Similarity Reports.This includes: files less than 100MB, files with a minimum of 20 words

  16. Assignment Operators in Programming

    Learn how to use assignment operators to assign values to variables and perform arithmetic operations in different programming languages. See examples of *= operator and other types of assignment operators in C, C++, Java, Python, and JavaScript.

  17. Python's Assignment Operator: Write Robust Assignments

    Learn how to use the assignment operator (=) to define, initialize, and modify variables in Python. Explore different types of assignment statements, augmented assignments, assignment expressions, and more.

  18. Type hints and chained assignment and multiple assignments

    For unpacking, per the same PEP, you should place bare annotations for your variables before the assignment. Example from the PEP: # Tuple unpacking with variable annotation syntax header: str kind: int body: Optional[List[str]] header, kind, body = message

  19. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...

  20. Type Conversion in Assignments

    Type Conversion in Assignments. In programming, it is common to assign one type of variable to another. For example, you might want to assign an int value to a float variable, as shown here:. When compatible types are mixed in an assignment, the value of the right side is automatically converted to the type of the left side.

  21. c

    Here: ptr_one = &x; ptr_two = &x; ptr_three = &y; ptr_one, ptr_two and ptr_three are int*s and &x and &y are double*s.You are trying to assign an int* with a double*.Hence the warning. Fix it by changing the types of the pointers to double* instead of int*, i.e, change the following lines. int *ptr_one; int *ptr_two; int *ptr_three;

  22. MyPy

    If you don't annotate a variable, mypy will infer its type based on the very first assignment it sees.. So in this case, the line c = int(_info.group(1)) appears first, so mypy decides that the type must be int.It then subsequently complains when it sees c = None.. One way of working around this limitation is to just forward-declare the variable with the expected type.