Index Numbers: Characteristics, Formula, Examples, Types, Importance and Limitations

assignment about index number

In this article we will discuss about:- 1. Meaning of Index Numbers 2. Features of Index Numbers 3. Steps or Problems in the Construction 4. Construction of Price Index Numbers (Formula and Examples) 5. Difficulties in Measuring Changes in Value of Money 6. Types of Index Numbers 7. Importance 8. Limitations.

Meaning of Index Numbers:

The value of money does not remain constant over time. It rises or falls and is inversely related to the changes in the price level. A rise in the price level means a fall in the value of money and a fall in the price level means a rise in the value of money. Thus, changes in the value of money are reflected by the changes in the general level of prices over a period of time. Changes in the general level of prices can be measured by a statistical device known as ‘index number.’

Index number is a technique of measuring changes in a variable or group of variables with respect to time, geographical location or other characteristics. There can be various types of index numbers, but, in the present context, we are concerned with price index numbers, which measures changes in the general price level (or in the value of money) over a period of time.

Price index number indicates the average of changes in the prices of representative commodities at one time in comparison with that at some other time taken as the base period. According to L.V. Lester, “An index number of prices is a figure showing the height of average prices at one time relative to their height at some other time which is taken as the base period.”

Features of Index Numbers:

ADVERTISEMENTS:

The following are the main features of index numbers:

(i) Index numbers are a special type of average. Whereas mean, median and mode measure the absolute changes and are used to compare only those series which are expressed in the same units, the technique of index numbers is used to measure the relative changes in the level of a phenomenon where the measurement of absolute change is not possible and the series are expressed in different types of items.

(ii) Index numbers are meant to study the changes in the effects of such factors which cannot be measured directly. For example, the general price level is an imaginary concept and is not capable of direct measurement. But, through the technique of index numbers, it is possible to have an idea of relative changes in the general level of prices by measuring relative changes in the price level of different commodities.

(iii) The technique of index numbers measures changes in one variable or group of related variables. For example, one variable can be the price of wheat, and group of variables can be the price of sugar, the price of milk and the price of rice.

(iv) The technique of index numbers is used to compare the levels of a phenomenon on a certain date with its level on some previous date (e.g., the price level in 1980 as compared to that in 1960 taken as the base year) or the levels of a phenomenon at different places on the same date (e.g., the price level in India in 1980 in comparison with that in other countries in 1980).

Steps or Problems in the Construction of Price Index Numbers:

The construction of the price index numbers involves the following steps or problems:

1. Selection of Base Year:

The first step or the problem in preparing the index numbers is the selection of the base year. The base year is defined as that year with reference to which the price changes in other years are compared and expressed as percentages. The base year should be a normal year.

In other words, it should be free from abnormal conditions like wars, famines, floods, political instability, etc. Base year can be selected in two ways- (a) through fixed base method in which the base year remains fixed; and (b) through chain base method in which the base year goes on changing, e.g., for 1980 the base year will be 1979, for 1979 it will be 1978, and so on.

2. Selection of Commodities:

The second problem in the construction of index numbers is the selection of the commodities. Since all commodities cannot be included, only representative commodities should be selected keeping in view the purpose and type of the index number.

In selecting items, the following points are to be kept in mind:

(a) The items should be representative of the tastes, habits and customs of the people.

(b) Items should be recognizable,

(c) Items should be stable in quality over two different periods and places.

(d) The economic and social importance of various items should be considered

(e) The items should be fairly large in number.

(f) All those varieties of a commodity which are in common use and are stable in character should be included.

3. Collection of Prices:

After selecting the commodities, the next problem is regarding the collection of their prices:

(a) From where the prices to be collected;

(b) Whether to choose wholesale prices or retail prices;

(c) Whether to include taxes in the prices or not etc.

While collecting prices, the following points are to be noted:

(a) Prices are to be collected from those places where a particular commodity is traded in large quantities.

(b) Published information regarding the prices should also be utilised,

(c) In selecting individuals and institutions who would supply price quotations, care should be taken that they are not biased.

(d) Selection of wholesale or retail prices depends upon the type of index number to be prepared. Wholesale prices are used in the construction of general price index and retail prices are used in the construction of cost-of-living index number.

(e) Prices collected from various places should be averaged.

4. Selection of Average:

Since the index numbers are, a specialised average, the fourth problem is to choose a suitable average. Theoretically, geometric mean is the best for this purpose. But, in practice, arithmetic mean is used because it is easier to follow.

5. Selection of Weights:

Generally, all the commodities included in the construction’ of index numbers are not of equal importance. Therefore, if the index numbers are to be representative, proper weights should be assigned to the commodities according to their relative importance.

For example, the prices of books will be given more weightage while preparing the cost-of-living index for teachers than while preparing the cost-of-living index for the workers. Weights should be unbiased and be rationally and not arbitrarily selected.

6. Purpose of Index Numbers:

The most important consideration in the construction of the index numbers is the objective of the index numbers. All other problems or steps are to be viewed in the light of the purpose for which a particular index number is to be prepared. Since, different index numbers are prepared with specific purposes and no single index number is ‘all purpose’ index number, it is important to be clear about the purpose of the index number before its construction.

7. Selection of Method:

The selection of a suitable method for the construction of index numbers is the final step.

There are two methods of computing the index numbers:

(a) Simple index number and

(b) Weighted index number.

Simple index number again can be constructed either by – (i) Simple aggregate method, or by (ii) simple average of price relative’s method. Similarly, weighted index number can be constructed either by (i) weighted aggregative method, or by (ii) weighted average of price relative’s method. The choice of method depends upon the availability of data, degree of accuracy required and the purpose of the study.

Construction of Price Index Numbers (Formula and Examples):

Construction of price index numbers through various methods can be understood with the help of the following examples:

1. Simple Aggregative Method:

In this method, the index number is equal to the sum of prices for the year for which index number is to be found divided by the sum of actual prices for the base year.

The formula for finding the index number through this method is as follows:

assignment about index number

  • Sahana Prasad 2  

388 Accesses

Index numbers are a type of economic indicator that represent the relative change in the value of a variable (e.g., price, quantity, production, income, etc.) compared to a base period or a reference point. They are used to simplify complex data and present it in a more understandable and comparable form.

This is a preview of subscription content, log in via an institution to check access.

Access this chapter

Subscribe and save.

  • Get 10 units per month
  • Download Article/Chapter or eBook
  • 1 Unit = 1 Article or 1 Chapter
  • Cancel anytime
  • Available as PDF
  • Read on any device
  • Instant download
  • Own it forever
  • Available as EPUB and PDF
  • Durable hardcover edition
  • Dispatched in 3 to 5 business days
  • Free shipping worldwide - see info

Tax calculation will be finalised at checkout

Purchases are for personal use only

Institutional subscriptions

Author information

Authors and affiliations.

RV University, Bengaluru, Karnataka, India

Sahana Prasad

You can also search for this author in PubMed   Google Scholar

Corresponding author

Correspondence to Sahana Prasad .

Rights and permissions

Reprints and permissions

Copyright information

© 2024 The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd.

About this chapter

Prasad, S. (2024). Index Numbers. In: Advanced Statistical Methods. Springer, Singapore. https://doi.org/10.1007/978-981-99-7257-9_2

Download citation

DOI : https://doi.org/10.1007/978-981-99-7257-9_2

Published : 12 May 2024

Publisher Name : Springer, Singapore

Print ISBN : 978-981-99-7256-2

Online ISBN : 978-981-99-7257-9

eBook Packages : Mathematics and Statistics Mathematics and Statistics (R0)

Share this chapter

Anyone you share the following link with will be able to read this content:

Sorry, a shareable link is not currently available for this article.

Provided by the Springer Nature SharedIt content-sharing initiative

  • Publish with us

Policies and ethics

  • Find a journal
  • Track your research

assignment about index number

Snapsolve any problem by taking a picture. Try it in the Numerade app?

Fundamentals of Applied Statistics

S c gupta, v k kapoor, index numbers - all with video answers.

Chapter Questions

What is an index number? Describe briefly the problems that are involved in the construction of an index number of prices.

(a) "Index numbers are economic barometers." Elucidate (b) "The index numbers are responsible to indicate an upward or downward trend in the value of the phenomenon (or variate) under study which help in the study of economic prosperity of the people of a certain area and so they are sometimes known as 'Economic Indicators'. Discuss.

(a) Discuss the importance and limitations of index numbers. Explain the various stages in the construction of the wholesale price index numbers of a set of a group of 'related variables'. (b) "Index numbers are devices for measuring differences in the magnitude of a group of related variables." Discuss the statement and point out the important uses of Index Numbers. (c) Discuss the problem of the construction of Index Number of wholesale price with special reference to $(i)$ selection of base period, (ii) selection of commodities and markets, (iii) selection of the type of average, and (iv) weighting.

(a) "Weighting is only one of the many problems in the construction of an index number." Discuss. What are the other major problems? (b) Explain the importance of using appropriate weights in framing index numbers and point out some iniportant systems of weighting. (c) Describe Laspeyre's and Paasche's methods of weighting index relatives. Which one would you prefer and why?

(a) Define the following Index Numbers and discuss their merits and demerits : (i) Laspeyre's Index number, (ii) Paasche's Index Number, and (iii) Fisher's Ideal Index Numbers. (b) 'It is sometimes stated that Laspeyer's price index tends to overestimate price changes while Paasche's price index tends to underestimate price changes." Substantiate this statement.

(a) (i) Explain the concept of an index number. (ii) Distinguish between aggregrative type and average type index number formulae. Develop Fisher's Ideal Index and examine its merits and demerits. (b) What are Marshall-Edgeworth, Laspeyre's and Paasche's index numbers? Prove that the Marshall-Edgeworth index number lies between Laspeyre's and Paasche's index numbers.

(a) Let $x=\left(p_1 / p_0\right), y=\left(q_1 / q_0\right), f_{x, y}=p_0 q_0, V_{01}=\left(\Sigma p_1 q_1 / \Sigma p_0 q_0\right)$. Show that $$ \frac{\left(\left[\Sigma p_1 q_0\right) /\left(\Sigma p_0 q_0\right)\right]}{\left[\left(\Sigma p_1 q_0\right) /\left(\Sigma p_0 q_0\right)\right]}=1-\frac{r_{x y} S_x S_y}{V_{01}} $$

Interpret this result in regard to the Laspeyre's and Paasche's Index Numbers. (b) If $L(p)$ and $P(q)$ represent Laspeyre's index number for prices and Paasche's index number for quantities, show that $$ L(p) \times P(q)=V_{01} $$ where $V_{01}$ is the value index number. Hence or otherwise show that $\frac{L(p)}{L(q)}=\frac{P(p)}{P(q)}$. Snow also that if $A(p)=\frac{1}{2}[L(p)+P(q)]$ then $A(p)$ is greater than the Fisher's Ideal Index Number. (c) Explain what is meant by 'bias' in an index number. Give an example of an index having an 'upward bias'. What is meant by reversibility of an index number? What index numbers are reversible?

(a) Define the terms: price relative, quantity relative and value relative and show how they are related to one another. (b) Explain briefly the methods of computing index numbers: (i) by the simple average of relatives method, (ii) by weighted aggregrative method, and (iii) by simple aggregrative method. 'Give an example for each method. (c) "The simple arithmetic average of relatives index number of prices has an upward bias," Discuss.

"For constructing index numbers, the best method on theoretical grounds is not the best method from practical point of view, so out of a long list of methods no method is real ideal." Comment.

(a) Outline the mathematical tests for an ideal index number. Illustrate these w.r.t. Fisher's ideal number. (b) Explain (i) Time Reversal test, (ii) Factor Reversal test, and (iii) Circular test, in index number theory. Give examples of index number satisfying one or more of the above tests. (c) What are the implications of 'Time Reversal' and 'Factor Reversal' tests ? In each case give one example of index number formula which (i) satisfies, (ii) does not satisfy, the test. Justify your statement.

What is an index number? Discuss its importance and uses. Explain : (i) Time reversal test, and (ii) Factor reversal test as applied to index numbers. Show that Fisher's ideal index number formula satisfies both these tests.

(c) Under what conditions will the Factor Reversal Test be satisfied by Laspeyre's price index? (b) Pr.we that Laspeyre's and Paasche's price index numbers satisfy. (i) The Time Reversal Test (ii) the Factor Reversal Test, if and only if both are equal.

(a) C.1€ck whether the following index numbers satisfy time reversal test and factor reversal test: $$ \begin{aligned} & \text { (iv) } I=\left(\frac{\Sigma p_1 q_1}{\Sigma p_0 f_1} \times \frac{\Sigma p_1 q_0}{\Sigma p_0 q_0}\right)^{1 / 2} \times 100 ;(v) I=\frac{\Sigma p_1\left(q_0+q_1\right)}{\Sigma p_0\left(q_0+q_1\right)} \times 100 \\ & \end{aligned} $$

Show that the index number : $$ I=\frac{\sum_r r\left\{p_{r a}\left(q_{r a}+q_{r b}\right)\right\}}{\sum_r r\left\{p_{r b}\left(q_{r a}+q_{r b}\right)\right\}} $$ obeys the time reversal test but not the circular test unless the weights in the three years $a, b, c$ are equal. Which other test, besides the two mentioned above, is used in connection with indices? Give at index which satisfies this test and show that it does so?

Explain clearly : (a) the chain base, and (b) the fixed base, methods in constructing an index number. Which method is more frequently used and why?

What is a Chain Index? What do you mean by 'circularity test"? Show that chain indices are equal to the corresponding fixed base indices if the formula used satisfies the circularity test. Discuss the advantages and disadvantages of the former over the latter.

(a) What are the various index numbers available for price statistics in India? Describe, is detail, the Economic Advisor's Index Number of Wholesale Prices in India. Do you find any practical utility of this index number to study the market situations in India? (b) Explain the procedure in the construction of Economic Adviser's wholesale price index number. Compare it with one other index of a similar nature.

(a) Write an essay on the Cost of Living Index Number in India. (b) Explain how you would construct the Cost of Living Index. What are the criticisms levelled against this index?

(a) What is meant by consumer price index? What are its uses? Describe the method of constructing consumer price index for industrial workers in India. (b) What is meant by family budget survey? Explain the method of constructing cost of living indes numbers. State their uses.

(a) What are the uses and limitations of a cost living index number? Describe in detail hos it is constructed in general. (b) What does the cost of living index measure? How do you derive the weights required in constructing this index? State the important uses of this index.

What is an index have to construct consumer's price index for mill workers in Mumbai. This index Suppose that you have thy. How will you select the commodities to be included in the construction of js to be published number? Give the names of at least six items that will be included and three that will be this indes number from the commodity list. How can you obtain the price-quotations of the items included? adided from the meant by (i) base shifting, (ii) deflating, and (iii) splicing of index numbers? Explain

(a) What is meant by (i) base shifting, (ii) deflating, and (iii) splicing of index numbers? Explain and illustrate. (b) What do you understand by deflating of index numbers? What is the need for deflating index nambers? Illustrate your answer with the help of an example.

(a) What factors should be considered for deciding as to how frequently it is desirable to change the base period of a price index number? (b) Explain the meaning and uses of cost of living index number. How are the weights assigned to the various groups and sub-groups?

What is a cost of living index number ? Discuss the following statement: "The cost of living indes number is essentially a consumer's price index." State the important steps involved in its construction.

Marcella Sippey

Describe briefly the Consumer Price Index for Urban Non-manual Employees, [(CPI (UNME)] in India.

Describe briefly the Consumer Price Index for Industrial workers [CPI (IW)] in India.

Describe briefly the Consumer Price Index for Agricultural Labourers CPI (AL) and Rural Lsbourers CPI (RL) in India.

Jennifer Stoner

(a) Explain the utility of the index numbers of business activity and industrial production. Describe a method of construction, in detail, of one of them. (b) State some of the difficulties that had to be faced in constructing an index number of industrial production and explain how that may be solved. What special technique has to be adopted in the case of a seasonal industry such as sugar? (c) What does an index number of industrial production attempt to measure? Describe the scope and method of construction of the current official index of industrial production. What are its limitations, if any and what steps would you suggest for its improvement?

Describe how Index Numbers of Industrial Production are constructed in India. Discuss in detail the latest services of IIP in India.

Describe briefly the indices of Agricultural Production in India.

Problem Questions with Answer, Solution | Applied Statistics - Exercise 9.2: Index Number | 12th Business Maths and Statistics : Chapter 9 : Applied Statistics

Chapter: 12th business maths and statistics : chapter 9 : applied statistics, exercise 9.2: index number.

Exercise 9.2

1. Define Index Number.

2. State the uses of Index Number.

3. Mention the classification of Index Number.

4. Define Laspeyre’s price index number.

5. Explain Paasche’s price index number.

6. Write note on Fisher’s price index number.

7. State the test of adequacy of index number.

8. Define Time Reversal Test.

9. Explain Factor Reversal Test.

10. Define true value ratio.

11. Discuss about Cost of Living Index Number.

12. Define Family Budget Method.

13. State the uses of Cost of Living Index Number.

14. Calculate by a suitable method, the index number of price from the following data:

assignment about index number

15. Calculate price index number for 2005 by (a) Laspeyre’s (b) Paasche’s method

assignment about index number

16. Compute (i) Laspeyre’s (ii) Paasche’s (iii) Fisher’s Index numbers for the 2010 from the following data.

assignment about index number

17. Using the following data, construct Fisher’s Ideal index and show how it satisfies Factor Reversal Test and Time Reversal Test?

assignment about index number

18. Using Fisher’s Ideal Formula, compute price index number for 1999 with 1996 as base year, given the following:

assignment about index number

19. Calculate Fisher’s index number to the following data. Also show that it satisfies Time Reversal Test.

assignment about index number

20. The following are the group index numbers and the group weights of an average working class family’s budget. Construct the cost of living index number:

assignment about index number

21. Construct the cost of living Index number for 2015 on the basis of 2012 from the following data using family budget method.

assignment about index number

22. Calculate the cost of living index by aggregate expenditure method:

assignment about index number

14. Laspeyre’s IN = 144.8 Paasche’s IN = 144.4

15. Laspeyre’s IN = 228.2 Paasche’s IN = 225.4

16. Laspeyre’s IN = 106.6 Paasche’s IN = 106.8 Fisher’s IN= 106.7

17. Fisher’s IN = 138.5 TRT= 1 FRT = 1880/1560

18. Fisher’s IN = 83

19. Fisher’s IN = 103 TRT = 1

20. Cost of Living Index =2662.38

21. Cost of Living Index = 117.31

22. Cost of Living Index = 131.49

Related Topics

Privacy Policy , Terms and Conditions , DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.

Index Number

Index Number

An index number is a number, which indicates the relative value of money from the prices of a limited number of goods at some standard date. It is the measure of the change in a variable (or group of variables) over time. It is a technique of measuring changes in a variable or group of variables with respect to time, geographical location, or other characteristics. They are a useful way of expressing economic data time series and comparing/contrasting information.

Index numbers are intended to measure the degree of economic changes over time. It is typically used in economics to measure trends in a wide variety of areas including – stock market prices, cost of living, industrial or agricultural production, and imports. The value of money does not remain constant over time. It rises or falls and is inversely related to the changes in the price level. Index numbers are important in economic statistics. A rise in the price level means a fall in the value of money and a fall in the price level means a rise in the value of money. Thus, changes in the value of money are reflected by the changes in the general level of prices over a period of time. Changes in the general level of prices can be measured by a statistical device known as ‘index number.’ In simple terms, an index (or index number) is a number displaying the level of a variable relative to its level (set equal to 100) in a given base period. For example, we are not able to directly measure changes in a country’s business activity.

Types of Index Numbers

  • Simple Index Number: A simple index number is a number that measures a relative change in a single variable with respect to a base.
  • Composite Index Number: A composite index number is a number that measures the average relative change in a group of relative variables with respect to a base.
  • Price index Numbers: Price index numbers measure the relative changes in prices of a commodity between two periods. Prices can be either retail or wholesale.
  • Quantity Index Numbers: These types of index numbers are considered to measure changes in the physical quantity of goods produced, consumed, or sold of an item or a group of items.

Characteristics of index numbers:

  • They are specialized averages.
  • These measure the change in the level of a phenomenon.
  • These measure the effect of changes over a period of time.

Social Enterprise

Social Enterprise

Gold as an investment

Gold as an investment

Advantages And Disadvantages Of Net Present Value

Advantages And Disadvantages Of Net Present Value

Cumulative Preference Shares

Cumulative Preference Shares

Cost Effective Account Service

Cost Effective Account Service

The Journey Of Ulysses

The Journey Of Ulysses

China’s Climate Push Might Create New Global Players, Even If Beijing Falls Short Of Its Goal

China’s Climate Push Might Create New Global Players, Even If Beijing Falls Short Of Its Goal

Historical Overview  of Solar Cells

Historical Overview of Solar Cells

Correlation Between Intracerebral Hemorrhage Score and Spontaneous Intracerebral Hemorrhage

Correlation Between Intracerebral Hemorrhage Score and Spontaneous Intracerebral Hemorrhage

How to Create Policy Document

How to Create Policy Document

Latest post.

Lithium Laurate – a metallorganic compound

Lithium Laurate – a metallorganic compound

AI may Help in Diagnosing Teenagers with ADHD

AI may Help in Diagnosing Teenagers with ADHD

A Gut Chemical Decreases Fat Burning while Fasting

A Gut Chemical Decreases Fat Burning while Fasting

Magnesium Orotate

Magnesium Orotate

Magnesium Malate

Magnesium Malate

Study Indicates Recommended Exercise for Type 1 Diabetic Patients

Study Indicates Recommended Exercise for Type 1 Diabetic Patients

  • Accountancy
  • Business Studies
  • Organisational Behaviour
  • Human Resource Management
  • Entrepreneurship

Methods of Construction of Index Number

What is index number.

A statistical measure that helps in finding out the percentage change in the values of different variables, such as the price of different goods, production of different goods, etc., over time is known as the Index Number. The percentage change is determined by taking a base year as a reference. This base year is the year of comparison. When an investigator studies different goods simultaneously, then the percentage change is considered the average for all the goods. 

There are two methods through which we can construct Index Numbers: viz., Simple or Unweighted and Weighted Index Numbers. 

1. Unweighted or Simple Index Numbers

An Index Number in which each item must have some weight as, no weight is expressly assigned to any item is known as Unweighted Index Number. It is also known as Simple Index Number and can be constructed with the help of two techniques; viz., Simple Aggregative Method and Simple Average of Price Relatives Method.

i) Simple Aggregative Method:

A method in which the aggregate prices of all the selected commodities in the current year are expressed as the aggregate price of all the commodities in the base year is known as Simple Aggregative Method. It is the simplest method to construct index number. The formula for constructing index number is:

P_{01}=\frac{\sum{p_1}}{\sum{p_0}}\times100

From the following data, construct Index Numbers for 2018-2019, taking 2010-2011 as the base year by using the Simple Aggregate Method.

Information Table

Price Index for year 2018-2019 with year 2010-2011 as the base:

P_{01}=\frac{\sum{p_1}}{\sum{p_0}}\times100=\frac{350}{250}\times100=140

The value of the Price Index (140) reveals that in the year 2018-2019, there is a net increase of 40% in the prices of given commodities as compared to the year 2010-2011.

ii) Simple Average of Price Relatives Method:

This index number is an improvement over the previous method, as it is not affected by the unit in which the prices of the commodities are quoted. The formula for constructing index number is:

P_{01}=\frac{\sum{(\frac{p_1}{p_0}\times100)}}{N}

From the following data, construct Index Numbers for 2018-2019, taking 2010-2011 as the base year by using Simple Average of Price Relatives Method.

Information Table

The Price Index Number (137.9) shows that there is an increase of 37.9% in the prices of commodities in the year 2018-2019 as compared in the year 2010-2011.

2. Weighted Index Numbers

In other index numbers, equal importance is given to each item. However, under Weighted Index Number, rational weights are given to each commodity or item explicitly. These weights indicate the relative importance of the commodities or items included in the determination of the index.

Here, rational weights mean the weights which are perfectly rational for one investigation. However, this weight might be unsuitable for other investigations. In fact, the purpose of the index number and the nature of the data concerned with it helps in deciding the rational weights.

There are two methods through which Weighted Index Numbers can be constructed; viz., Weighted Aggregative Method and Weighted Average of Price Relatives Method.

i) Weighted Aggregative Method:

This method involves assigning weights to different items and obtaining weighted aggregate of the prices instead of finding a simple aggregate of prices. Some important methods of constructing Weighted Aggregative Index are as follows:

  • Laspeyre’s Method
  • Paasche’s Method
  • Fisher’s Ideal Method
  • Drobish and Bowley’s Method
  • Marshall Edgeworth Method
  • Walsch’s Method
  • Kelly’s Method

a) Laspeyre’s Method

The method of calculating Weighted Index Numbers under which the base year quantities are used as weights of different items is known as Laspeyre’s Method. The formula for Laspeyre’s Price Index is:

Laspeyre's~Price~Index~(P_{01})=\frac{\sum{p_1q_0}}{\sum{p_0q_0}}\times{100}

The following are the price and quantity of four commodities A, B, C, and D, in 2015 and 2020. Construct index number of prices in the year 2020 using Laspeyre’s Method. 

Information Table

The Index Number of Price using Laspeyre’s Method is 62.84 .

b) Paasche’s Method

The method of calculating Weighted Index Numbers under which the current year’s quantities are used as weights of different items is known as Paasche’s Method. The formula for Paasche’s Price Index is:

Paasche's~Index~Number~(P_{01})=\frac{\sum{p_1q_1}}{\sum{p_0q_1}}\times{100}

The following are the price and quantity of four commodities A, B, C, and D, in 2015 and 2020. Construct index number of prices in the year 2020 using Paasche’s Method. 

Information Table

The Index Number using Paasche’s Price Index is 51.2

c) Fisher’s Method

The method of calculating Weighted Index Numbers under which the combined techniques of Paasche and Laspeyre are used is known as Fisher’s Method. In other words, both the base year and current year’s quantities are used as weights. The formula for Fisher’s Price Index is:

Fisher's~Price~Index~(P_{01})=\sqrt{\frac{\sum{p_1q_0}}{\sum{p_0q_0}}\times{\frac{\sum{p_1q_1}}{\sum{p_0q_1}}}}\times{100}

Fisher’s Method is considered the Ideal Method for Constructing Index Numbers.

The following are the price and quantity of four commodities A, B, C, and D, in 2015 and 2020. Construct index number of prices in the year 2020 using Fisher’s Method. 

Information Table

The Index Number using Fisher’s Price Index is 56.72

ii) Weighted Average of Price Relatives Method:

Under this method, the base year prices of the commodities are taken as the basis to calculate the price relatives for the current year. The calculated price relatives are then multiplied by their respective weights of the items. After that, the products determined are added up and divided by the sum of weights. The formula for constructing index number is:

P_{01}=\frac{\sum{RW}}{\sum{W}}

Use Weighted Relatives Method and determine the index number from the following data for the year 2019 with 2008 as the base year.

Information Table

Weighted Average of Price Relatives

\frac{1,91,500}{939}=203.9

The Index Number of 204 shows that there is an increase of 104% in the prices in the year 2019 as compared to the year 2008.

Please Login to comment...

Similar reads.

  • Statistics for Economics
  • Commerce - 11th
  • How to Watch NFL Games Live Streams Free
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Indexing on ndarrays #

Indexing routines

ndarrays can be indexed using the standard Python x[obj] syntax, where x is the array and obj the selection. There are different kinds of indexing available depending on obj : basic indexing, advanced indexing and field access.

Most of the following examples show the use of indexing when referencing data in an array. The examples work just as well when assigning to an array. See Assigning values to indexed arrays for specific examples and explanations on how assignments work.

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

Basic indexing #

Single element indexing #.

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

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

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

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

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

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

Slicing and striding #

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

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

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

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

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

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

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

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

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

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

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

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

The above is not true for advanced indexing.

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

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

Dimensional indexing tools #

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

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

This is equivalent to:

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

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

Advanced indexing #

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

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

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

Integer array indexing #

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

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

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

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

Advanced indices always are broadcast and iterated as one :

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

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

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

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

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

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

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

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

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

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

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

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

This broadcasting can also be achieved using the function ix_ :

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

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

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

Boolean array indexing #

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

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

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

Or wish to add a constant to all negative elements:

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

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

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

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

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

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

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

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

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

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

Combining advanced and basic indexing #

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

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

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

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

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

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

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

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

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

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

Slicing can be combined with broadcasted boolean indices:

Field access #

Structured arrays

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

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

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

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

Flat iterator indexing #

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

Assigning values to indexed arrays #

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

or an array of the right size:

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

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

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

Dealing with variable numbers of indices within programs #

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

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

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

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

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

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

Detailed notes #

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

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

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

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

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

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

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

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

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

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

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

IndexError: list assignment index out of range in Python

avatar

Last updated: Apr 8, 2024 Reading time · 9 min

banner

# Table of Contents

  • IndexError: list assignment index out of range
  • (CSV) IndexError: list index out of range
  • sys.argv[1] IndexError: list index out of range
  • IndexError: pop index out of range
Make sure to click on the correct subheading depending on your error message.

# IndexError: list assignment index out of range in Python

The Python "IndexError: list assignment index out of range" occurs when we try to assign a value at an index that doesn't exist in the list.

To solve the error, use the append() method to add an item to the end of the list, e.g. my_list.append('b') .

indexerror list assignment index out of range

Here is an example of how the error occurs.

assignment to index out of range

The list has a length of 3 . Since indexes in Python are zero-based, the first index in the list is 0 , and the last is 2 .

abc
012

Trying to assign a value to any positive index outside the range of 0-2 would cause the IndexError .

# Adding an item to the end of the list with append()

If you need to add an item to the end of a list, use the list.append() method instead.

adding an item to end of list with append

The list.append() method adds an item to the end of the list.

The method returns None as it mutates the original list.

# Changing the value of the element at the last index in the list

If you meant to change the value of the last index in the list, use -1 .

change value of element at last index in list

When the index starts with a minus, we start counting backward from the end of the list.

# Declaring a list that contains N elements and updating a certain index

Alternatively, you can declare a list that contains N elements with None values.

The item you specify in the list will be contained N times in the new list the operation returns.

Make sure to wrap the value you want to repeat in a list.

If the list contains a value at the specific index, then you are able to change it.

# Using a try/except statement to handle the error

If you need to handle the error if the specified list index doesn't exist, use a try/except statement.

The list in the example has 3 elements, so its last element has an index of 2 .

We wrapped the assignment in a try/except block, so the IndexError is handled by the except block.

You can also use a pass statement in the except block if you need to ignore the error.

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

# Getting the length of a list

If you need to get the length of the list, use the len() function.

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

If you need to check if an index exists before assigning a value, use an if statement.

This means that you can check if the list's length is greater than the index you are trying to assign to.

# Trying to assign a value to an empty list at a specific index

Note that if you try to assign to an empty list at a specific index, you'd always get an IndexError .

You should print the list you are trying to access and its length to make sure the variable stores what you expect.

# Use the extend() method to add multiple items to the end of a list

If you need to add multiple items to the end of a list, use the extend() method.

The list.extend method takes an iterable (such as a list) and extends the list by appending all of the items from the iterable.

The list.extend method returns None as it mutates the original list.

# (CSV) IndexError: list index out of range in Python

The Python CSV "IndexError: list index out of range" occurs when we try to access a list at an index out of range, e.g. an empty row in a CSV file.

To solve the error, check if the row isn't empty before accessing it at an index, or check if the index exists in the list.

csv indexerror list index out of range

Assume we have the following CSV file.

And we are trying to read it as follows.

# Check if the list contains elements before accessing it

One way to solve the error is to check if the list contains any elements before accessing it at an index.

The if statement checks if the list is truthy on each iteration.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False .
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

# Check if the index you are trying to access exists in the list

Alternatively, you can check whether the specific index you are trying to access exists in the list.

This means that you can check if the list's length is greater than the index you are trying to access.

# Use a try/except statement to handle the error

Alternatively, you can use a try/except block to handle the error.

We try to access the list of the current iteration at index 1 , and if an IndexError is raised, we can handle it in the except block or continue to the next iteration.

# sys.argv [1] IndexError: list index out of range in Python

The sys.argv "IndexError: list index out of range in Python" occurs when we run a Python script without specifying values for the required command line arguments.

To solve the error, provide values for the required arguments, e.g. python main.py first second .

sys argv indexerror list index out of range

I ran the script with python main.py .

The sys.argv list contains the command line arguments that were passed to the Python script.

# Provide all of the required command line arguments

To solve the error, make sure to provide all of the required command line arguments when running the script, e.g. python main.py first second .

Notice that the first item in the list is always the name of the script.

It is operating system dependent if this is the full pathname or not.

# Check if the sys.argv list contains the index

If you don't have to always specify all of the command line arguments that your script tries to access, use an if statement to check if the sys.argv list contains the index that you are trying to access.

I ran the script as python main.py without providing any command line arguments, so the condition wasn't met and the else block ran.

We tried accessing the list item at index 1 which raised an IndexError exception.

You can handle the error or use the pass keyword in the except block.

# IndexError: pop index out of range in Python

The Python "IndexError: pop index out of range" occurs when we pass an index that doesn't exist in the list to the pop() method.

To solve the error, pass an index that exists to the method or call the pop() method without arguments to remove the last item from the list.

indexerror pop index out of range

The list has a length of 3 . Since indexes in Python are zero-based, the first item in the list has an index of 0 , and the last an index of 2 .

If you need to remove the last item in the list, call the method without passing it an index.

The list.pop method removes the item at the given position in the list and returns it.

You can also use negative indices to count backward, e.g. my_list.pop(-1) removes the last item of the list, and my_list.pop(-2) removes the second-to-last item.

Alternatively, you can check if an item at the specified index exists before passing it to pop() .

This means that you can check if the list's length is greater than the index you are passing to pop() .

An alternative approach to handle the error is to use a try/except block.

If calling the pop() method with the provided index raises an IndexError , the except block is run, where we can handle the error or use the pass keyword to ignore it.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • IndexError: index 0 is out of bounds for axis 0 with size 0
  • IndexError: invalid index to scalar variable in Python
  • IndexError: pop from empty list in Python [Solved]
  • Replacement index 1 out of range for positional args tuple
  • IndexError: too many indices for array in Python [Solved]
  • IndexError: tuple index out of range in Python [Solved]

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

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
  • Using and Creating Global Variables in Your Python Functions
  • Iterators and Iterables in Python: Run Efficient Iterations
  • The Python return Statement: Usage and Best Practices

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.

assignment about index number

List Index Out of Range – Python Error Message Solved

Dionysia Lemonaki

In this article you'll see a few of the reasons that cause the list index out of range Python error.

Besides knowing why this error occurs in the first place, you'll also learn some ways to avoid it.

Let's get started!

How to Create a List in Python

To create a list object in Python, you need to:

  • Give the list a name,
  • Use the assignment operator, = ,
  • and include 0 or more list items inside square brackets, [] . Each list item needs to be separated by a comma.

For example, to create a list of names you would do the following:

The code above created a list called names that has four values: Kelly, Nelly, Jimmy, Lenny .

How to Check the Length of a List in Python

To check the length of a list in Python, use Python's build-in len() method.

len() will return an integer, which will be the number of items stored in the list.

There are four items stored in the list, therefore the length of the list will be four.

How to Access Individual List Items in Python

Each item in a list has its own index number .

Indexing in Python, and most modern programming languages, starts at 0.

This means that the first item in a list has an index of 0, the second item has an index of 1, and so on.

You can use the index number to access the individual item.

To access an item in a list using its index number, first write the name of the list. Then, inside square brackets, include the intiger that corresponds with the item's index number.

Taking the example from earlier, this is how you would access each item inside the list using its index number:

You can also use negative indexing to access items inside lists in Python.

To access the last item, you use the index value of -1. To acces the second to last item, you use the index value of -2.

Here is how you would access each item inside a list using negative indexing:

Why does the Indexerror: list index out of range error occur in Python?

Using an index number that is out of the range of the list.

You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist.

This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.

Let's go back to the list we've used so far.

Say I want to access the last item, "Lenny", and try to do so by using the following code:

Generally, the index range of a list is 0 to n-1 , with n being the total number of values in the list.

With the total values of the list above being 4 , the index range is 0 to 3 .

Now, let's try to access an item using negative indexing.

Say I want to access the first item in the list, "Kelly", by using negative indexing.

When using negative indexing, the index range of a list is -1 to -n , where -n the total number of items contained in the list.

With the total number of items in the list being 4 , the index range is -1 to -4 .

Using the wrong value in the range() function in a Python for loop

You'll get the Indexerror: list index out of range error when iterating through a list and trying to access an item that doesn't exist.

One common instance where this can occur is when you use the wrong integer in Python's range() function.

The range() function typically takes in one integer number, which indicates where the counting will stop.

For example, range(5) indicates that the counting will start from 0 and end at 4 .

So, by default, the counting starts at position 0 , is incremented by 1 each time, and the number is up to – but not including – the position where the counting will stop.

Let's take the following example:

Here, the list names has four values.

I wanted to loop through the list and print out each value.

When I used range(5) I was telling the Python interpreter to print the values that are at the positions 0 to 4 .

However, there is no item in position 4.

You can see this by first printing out the number of the position and then the value at that position.

You see that at position 0 is "Kelly", at position 1 is "Nelly", at position 2 is "Jimmy" and at position 3 is "Lenny".

When it comes to position four, which was specified with range(5) which indicates positions of 0 to 4 , there is nothing to print out and therefore the interpreter throws an error.

One way to fix this is to lower the integer in range() :

Another way to fix this when using a for loop is to pass the length of the list as an argument to the range() function. You do this by using the len() built-in Python function, as shown in an earlier section:

When passing len() as an argument to range() , make sure that you don't make the following mistake:

After running the code, you'll again get an IndexError: list index out of range error:

Hopefully this article gave you some insight into why the IndexError: list index out of range error occurs and some ways you can avoid it.

If you want to learn more about Python, check out freeCodeCamp's Python Certification . You'll start learning in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

Read more posts .

If this article was helpful, share it .

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

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

python : IndexError: list assignment index out of range

i wrote this program :

and when i run it they say

please do you have any solutions ??

Haytam Rahimi's user avatar

  • 3 What do you precisely want to do at this step del l[min(l)] ? Consider a list [10, 20, 30] now image the execution of del l[min(l)] . This would be del l[10] , but there is not 10th element in the list and hence shows error –  ZdaR Commented Mar 8, 2017 at 18:48
  • 1 Suppose l is [23, 42, 99]. Then del l[min(l)] is equivalent to del l[23] , which is equivalent to "delete the 24th element of l". But l doesn't have 24 elements, it has three elements. –  Kevin Commented Mar 8, 2017 at 18:49

2 Answers 2

Your problem is that del l[min(l)] is trying to reference the list item at index min(l) . Let's assume that your list has 3 items in it:

Trying to delete the item at the index min(l) is referencing the index 17, which doesn't exist. Only indices 0, 1, and 2 exist.

I think what you want to do is remove the smallest item from your list sequentially. There are a number of ways to do this. The method that is closest to what you have written would be:

James's user avatar

Reason : Because you want to delete element holding index of min element and not index=min element

O/P : (for input 1 2 3 4 5)

[2, 3, 4, 5]

minigeek's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

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

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Determining Entropy in PHP
  • HTA w/ VBScript to open and copy links
  • Movie from the fifties where aliens look human but wear sunglasses to hide that they have no irises (color) in their eyes - only whites!
  • Cartoon Network (Pakistan or India) show around 2007 or 2009 featuring a brother and sister who fight but later become allies
  • tikczd: how move label on one arrow
  • Is SQL .bak file compressed without explicitly stating to compress?
  • How to use js in carousel code into a functional Next.js component for scrolling support in headless sitecore
  • Craig interpolants for Linear Temporal Logic: finding one when they exist
  • Is internal energy depended on the acceleration of the system?
  • meaning of a sentence from Agatha Christie (Murder of Roger Ackroyd)
  • Missed the application deadline for a TA job. Should I contact them?
  • crontab schedule on Alpine Linux runs on days it's not supposed to run on
  • How to react to a rejection based on a single one-line negative review?
  • How to plausibly delay the creation of the telescope
  • converting a non-unitary matrix into quantum circuit
  • How to rectify a mistake in DS 160
  • How can I calculate derivative of eigenstates numerically?
  • How can I use an op-amp in differential configuration to measure voltage across a MOSFET?
  • On Concordant Readings in Titrations
  • Use the lower of two voltages when one is active
  • Cutting a curve through a thick timber without waste
  • '05 Scion tC, bought used. 145k miles , unknown if spark plugs were ever changed. Should I change 'em?
  • Symbolic integral over real functions with interger parametres evaluates to complex numbers
  • Would a scientific theory of everything be falsifiable?

assignment about index number

Suspect in Trump apparent assassination attempt hit with gun charges, media report

  • Medium Text

Ryan W. Routh, a suspect identified by news organizations, as the FBI investigates what they said was an apparent assassination attempt on former U.S. President Trump in Florida is seen in Kyiv

Sign up here.

Reporting by Caitlin Webber; editing by Rami Ayyub

Our Standards: The Thomson Reuters Trust Principles. , opens new tab

Police continue investigation of gunman at Trump International Golf Club in West Palm Beach

Hezbollah members wounded in Lebanon when pagers explode

More than 1,000 people were wounded in the attack. The detonation of the pagers was the "biggest security breach" the group had been subjected to in nearly a year of war, a Hezbollah official said.

An airplane drops water on a wildfire along A25 Highway, near Freixiosa

  • Share full article

Advertisement

Supported by

Portugal Going Through ‘Difficult Days’ as Wildfires Burn Across the Country

More than 5,000 personnel are battling a number of wildfires, the authorities said, and the prime minister called it an “extremely difficult weather situation.”

A helicopter carrying a vessel from a rope drops water on a forested area blanked in smoke, with flames visible in the trees.

By Derrick Bryson Taylor

Sweeping wildfires across Portugal this week fueled by scorching heat have caused multiple deaths, disrupted travel and prompted a coordinated response from multiple local and international governments.

The fires, caused by dry brush and exacerbated by heat and strong winds, have been concentrated in the central and northern parts of the country but have been reported all over.

At least four people have died since the fires began over the weekend, according to Publico , a national newspaper in Portugal, and residents have had to flee their homes to safety. It is unclear exactly how many acres have been burned so far, but more than 5,000 personnel were working around Portugal to get the flames under control, according to the country’s National Emergency and Civil Protection Authority.

Prime Minister Luís Montenegro of Portugal said on social media on Monday that one of the deaths was a firefighter who died of a “sudden illness” while fighting a fire in Oliveira de Azeméis, a region more than 30 miles southeast of Porto.

A number of other firefighters have been injured, including at least four in Albergaria-a-Velha , a region farther south where more than 400 firefighters are on the ground.

Scattered wildfires across the country have grown so severe that train service in some regions has been restricted, and at least six major roadways have been partly or fully closed. With temperatures expected to remain high this week, the National Emergency and Civil Protection Authority extended a rural fire danger alert through the end of Thursday.

“Portugal is going through difficult days due to wildfires,” Mr. Montenegro said on social media .

A statement from Mr. Montenegro’s office on Monday said that the prime minister was overseeing the coordination of the fight against the fires across the country “in this extremely difficult weather situation.”

He also called on leaders of the European Union and European partners, asking for additional support.

Ursula von der Leyen, the European Commission president, said on social media that the European Union was lending aid. “We are urgently mobilizing eight firefighting planes via our Civil Protection Mechanism to help local first responders,” she said. “I thank France, Greece, Italy and Spain for their rapid reaction. This is E.U. solidarity at its best.”

Wildfires continue to ramp up across the country, and temperatures in various regions are expected to reach the mid 80s on Tuesday with no rain expected for at least a few days.

The government of Portugal issued fire prevention guidelines to the public. Officials have asked residents to notify neighbors if fire is detected near their homes, turn off the gas and thoroughly wet the walls and bushes surrounding the house. The authorities have also asked residents to report any risky behavior that could result in fire.

Derrick Bryson Taylor covers breaking and trending news and is based in London. More about Derrick Bryson Taylor

IMAGES

  1. Types of Index Numbers Assignment Help

    assignment about index number

  2. Index Numbers Practice problems

    assignment about index number

  3. Index Numbers worksheet

    assignment about index number

  4. Index Number

    assignment about index number

  5. Index Numbers: Characteristics, Formula, Examples, Types, Importance

    assignment about index number

  6. SOLUTION: Index number detailed explanations with examples

    assignment about index number

VIDEO

  1. Index Number- Introduction,Methods of Construction of Index Number, Simple Aggregate Method| Part-1

  2. Index content for Assignment

  3. finding unit digit in number of index form

  4. Number system assignment Index

  5. Index design for school projects and assignments 🌷

  6. How to Make Index Page For Project File/Assignment

COMMENTS

  1. Index Numbers: Characteristics, Formula, Examples, Types, Importance

    Index number is a technique of measuring changes in a variable or group of variables with respect to time, geographical location or other characteristics. There can be various types of index numbers, but, in the present context, we are concerned with price index numbers, which measures changes in the general price level (or in the value of money) over a period of time.

  2. Index Number

    Croxton and Cowden. "An index number is a statistical measure designed to show changes in variable or a group of related variables with respect to time, geographical location or other characteristics.". - Spiegel. An index number is used to display changes in a variable or group of related variables through time, space, or other factors.

  3. Unit 4

    What is an index number? A number that expresses the relative change in price, quantity, or value compared to a base number.

  4. PDF 11 INDEX NUMBERS

    11.1 MEANING OF INDEX NUMBER "An index number is a statistical measure, designed to measure changes in a variable, or a group of related variables". r situations". INDEX NUMBER expresses the relative change in price, quantity, or value compared

  5. PDF INDEX NUMBERS

    "Index number is a single ratio (or a percentage) which measures the combined change of several variables between two different times, places or situations". We can thus say that index numbers are economic barometers to judge the inflation ( increase in prices) or deflationary (decrease in prices ) tendencies of the economy.

  6. Index Numbers

    The index number for 2015 is 97.4 and the index number for 2020 is 107.2. (b) Find the percentage change in the price of thingummies from 2012 to 2015. Be sure to specify whether it is an increase or a decrease. Subtract 100 from the index number for 2015 to find the percentage change.

  7. Index Numbers

    Weighted index numbers: A type of index number in which rational weights are assigned to various entities as per their importance. It is calculated as, the ratio between the summation of the product of weights with price relatives and the summation of the weights.

  8. Chapter 9, Index Numbers : Concepts and Applications Video Solutions

    Video answers for all textbook questions of chapter 9, Index Numbers : Concepts and Applications, Business Statistics by Numerade

  9. Chapter 3, INDEX NUMBERS Video Solutions, Fundamentals of Applied

    Problem 3. (a) Discuss the importance and limitations of index numbers. Explain the various stages in the construction of the wholesale price index numbers of a set of a group of 'related variables'. (b) "Index numbers are devices for measuring differences in the magnitude of a group of related variables." Discuss the statement and point out ...

  10. PDF Index Numbers

    1.2 Definition of an index number Index numbers are statistical devices designed to measure the relative change in the level of a phenomenon with respect to time, geographical location or other characteristics.

  11. Index Numbers in General

    Index Numbers (Source: NationRanking) So what are index numbers? Well, technically speaking, an index number is a statistical measure designed to show changes in a variable or group of related variables with respect to time, geographic location or other characteristics. Let's understand this with an example. Suppose the price of a certain product doubles relative to a year. As a result of ...

  12. Quantity Index Numbers: Methods for calculating this Index Number

    What is an Index Number? Very simply put, index numbers help us observe the change in some quantity that we cannot otherwise easily observe or measure. For example, we cannot directly measure the growth of business activity in an economy. However, we can study the changes in factors that influence this business activity.

  13. Exercise 9.2: Index Number

    Exercise 9.2: Index Number Book back answers and solution for Exercise questions - Maths: Applied Statistics: Index Number: Problem Questions with Answer, Solution Exercise 9.2 1. Define Index Number. 2. State the uses of Index Number.

  14. Index Number

    An index number is a number, which indicates the relative value of money from the prices of a limited number of goods at some standard date. It is the measure of the change in a variable (or group of variables) over time. It is a technique of measuring changes in a variable or group of variables with respect to time, geographical location, or other characteristics. They are a useful way of ...

  15. Methods of Construction of Index Number

    An Index Number in which each item must have some weight as, no weight is expressly assigned to any item is known as Unweighted Index Number. It is also known as Simple Index Number and can be constructed with the help of two techniques; viz., Simple Aggregative Method and Simple Average of Price Relatives Method.

  16. python

    Why can't I build a list by assigning each element in turn? How can I add (append) the elements without getting an IndexError? Asked 13 years, 5 months ago Modified 2 months ago Viewed 727k times

  17. Indexing on ndarrays

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

  18. IndexError: list assignment index out of range in Python

    The Python IndexError: list assignment index out of range occurs when we try to assign a value at an index that doesn't exist in the list.

  19. Python's Assignment Operator: Write Robust Assignments

    In this tutorial, you'll learn how to use Python's assignment operators to write assignment statements that allow you to create, initialize, and update variables in your code.

  20. How to assign the value of an index of a list to a variable in Python

    You are saying you want to take the index value of the first element of the list and assign that the value 0 to a variable. But the index of the first value of a list will always be 0.

  21. How to solve the error 'list assignment index out of range' in python

    2 I try to store the number of weekofyear from the list of data named date_range which stored the data such as

  22. Drinking 1 to 3 cups of coffee a day may protect heart health

    The caffeine in your coffee or tea might not just be a daily vice — it could be reducing your risk for heart disease, according to new research.

  23. List Index Out of Range

    Generally, the index range of a list is 0 to n-1, with n being the total number of values in the list. With the total values of the list above being 4, the index range is 0 to 3.

  24. Biden administration says number of illegal border crossings has ...

    US officials on Monday touted another month of low border crossings, citing recent executive action curbing asylum access at the US southern border, even as former President Donald Trump levels ...

  25. python : IndexError: list assignment index out of range

    Only indices 0, 1, and 2 exist. I think what you want to do is remove the smallest item from your list sequentially. There are a number of ways to do this. The method that is closest to what you have written would be: for i in range(N): l.remove(min(l)) print(l) answered Mar 8, 2017 at 18:55. James.

  26. How Secret Service Details Are Assigned

    The Secret Service would not disclose the exact number of agents and different types of protective resources assigned to the around 40 people it currently protects.

  27. Suspect in Trump apparent assassination attempt hit with gun charges

    Ryan Routh, the reported suspect in an apparent assassination attempt on former President Donald Trump on Sunday, has been charged with two federal gun charges, CNN and other U.S. media outlets ...

  28. Portugal Going Through 'Difficult Days' as Wildfires Burn Across the

    More than 5,000 personnel are battling a number of wildfires, the authorities said, and the prime minister called it an "extremely difficult weather situation." Share full article