Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Difference between Strings and Lists in Python (http://www.go4expert.com/articles/difference-strings-lists-python-t27973/)

lionaneesh 7Mar2012 17:19

Difference between Strings and Lists in Python
 
Strings and Lists are 2 important data types in the suite of structured data types in python. Strings and lists are similar, but they are not same and many people don’t know the main difference between a string and a list in python. One simple difference between strings and lists is that lists can any type of data i.e. integers, characters, strings etc, while strings can only hold a set of characters.

Let’s try the following set of Code:-

Code: python

s = [‘H’,’e’,’l’,’l’,’o’]
s[0] = 'Y'
print s

Output:-

Code: python

['Y','e','l','l','o']

As expected it works fine.

Now let’s try the same with strings:-

Code: python

s = 'Hello'
s[0] = 'Y'

print s

Output:-

Code:

s[0] = 'Y'
TypeError: 'str' object does not support item assignment

Another Main difference between stings and lists which we’ll discuss in this tutorial is Mutation.

Mutation



Though it sounds scary, mutation is actually a very simple concept. What Mutation means is that we can change the value of a list after we have created it, but we cannot in case of strings, one might question that we can change a value of a string by using operators such as concatenation, assignment etc.

Assignment

Code: python

S = ‘Hello’
S = ‘Yellow’

The above code changed the value of the variable s and not the value of the string, what happens behind the scenes is that python declared 2 strings “Hello” and “Yellow” and these strings are saved somewhere in the memory, in the first line s points to the string “Hello” and in the second the string point to “Yellow”. These can be imagined as pointers in C.

Concatenation

Code: python

S = ‘Hello’
S = S + ‘z’

In the above code we first assign S the string “Hello” and then in the next line we set it to the concatenated output of Hello + z i.e Helloz.

What Python is doing behind the scenes is that I declared 2 strings i.e ‘Hello’ , ‘z’ now after the concatenation the value of the string is not changed but instead it creates a new string, ‘Helloz’ and then by assignment S now points to this string.

Conclusion



The purpose of this article was to introduce the reader about the main differences in strings and lists especially, Mutation. The main motive was to provide a clear picture of what python is doing behind the scenes and what we can expect from that.

Copywriter 28Apr2012 23:46

Re: Difference between Strings and Lists in Python
 
Thank you to share useful post. Its real ye very informative for me and other.


All times are GMT +5.5. The time now is 09:28.