Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a[:]=1 fundamentally different to a[:]='1'?

Tags:

python

Please consider the two snippets of code (notice the distinction between string and integer):

a = [] a[:] = '1' 

and

a = [] a[:] = 1 

In the first case a is ['1']. In the second, I get the error TypeError: can only assign an iterable. Why would using '1' over 1 be fundamentally different here?

like image 888
Randomblue Avatar asked Jan 28 '12 12:01

Randomblue


People also ask

What is a 1 1 correlation?

A correlation coefficient, often expressed as r, indicates a measure of the direction and strength of a relationship between two variables. When the r value is closer to +1 or -1, it indicates that there is a stronger linear relationship between the two variables.

What is the correlation between two variables?

Correlation is a statistical term describing the degree to which two variables move in coordination with one another. If the two variables move in the same direction, then those variables are said to have a positive correlation. If they move in opposite directions, then they have a negative correlation.

What does it mean to say that the linear correlation coefficient between two variables equals 1 What would the scatter diagram look like?

When the linear correlation coefficient is 1, there is a perfect horizontal linear relation between the two variables. The scatter diagram would contain points that all lie on a horizontal line.

What does the correlation coefficient tell you?

The correlation coefficient is the specific measure that quantifies the strength of the linear relationship between two variables in a correlation analysis.


2 Answers

Assigning to a slice requires an iterable on the right-hand side.

'1' is iterable, while 1 is not. Consider the following:

In [7]: a=[]  In [8]: a[:]='abc' 

The result is:

In [9]: a Out[9]: ['a', 'b', 'c'] 

As you can see, the list gets each character of the string as a separate item. This is a consequence of the fact that iterating over a string yields its characters.

If you want to replace a range of a's elements with a single scalar, simply wrap the scalar in an iterable of some sort:

In [11]: a[:]=(1,) # single-element tuple  In [12]: a Out[12]: [1] 

This also applies to strings (provided the string is to be treated as a single item and not as a sequence of characters):

In [17]: a[:]=('abc',)  In [18]: a Out[18]: ['abc'] 
like image 142
NPE Avatar answered Oct 22 '22 22:10

NPE


'1' is a string, but it is iterable. It is like a list of characters. a[:]='1' replaces the contents of the list a with the content of the string '1'. But 1 is an integer.

Python does not change the type.

Example:

print bool(1=='1') # --> False 
like image 36
guettli Avatar answered Oct 22 '22 22:10

guettli