In [1]:
list('hello!')
Out[1]:
['h', 'e', 'l', 'l', 'o', '!']
In [2]:
name = 'Moriarty'
In [3]:
name[0]
Out[3]:
'M'
In [4]:
name[1:3]
Out[4]:
'or'
In [5]:
name[-1]
Out[5]:
'y'
In [6]:
'Mo' in name
Out[6]:
True
In [7]:
'James' in name
Out[7]:
False
In [8]:
for letter in name:
    print(letter)
M
o
r
i
a
r
t
y


A list value is a Mutable data type and a string value is Immuble data type i.e we can add, remove values in list, but not in strings



Now let's see some interesting/weird thing now

In [9]:
name = 'Moriarty'
In [10]:
something = name
In [11]:
name = 'Scresat'
In [12]:
name
Out[12]:
'Scresat'
In [13]:
something
Out[13]:
'Moriarty'

So far so good...

Let's do that same thing, now with the list.

In [14]:
name = [0,1,2,3,4,5]
In [15]:
something = name
In [16]:
something[1] = 'Hello!'
In [17]:
something
Out[17]:
[0, 'Hello!', 2, 3, 4, 5]

Now comes the weird part

In [18]:
name
Out[18]:
[0, 'Hello!', 2, 3, 4, 5]

The original list is changed!

Reason - Variables don't contain list, they contain references to the list

Explanation - When the list [0,1,2,3,4,5] is created, the list gets stored in the memort, and name here references it. so when we create another variable, in this case something and assign value of name to it, it doesn't create new list just for 'something', it merely creates new reference to the original list [0,1,2,3,4,5] which is stored in memory.

So when we modify one reference, here it is 'something', it modifies the list to which it is referenced to in the memory. That in change changes the values of the other variables since it is variables are merely a references.

Same thing applies to other mutable data types.


Conceps of global and local scope doesn't apply in the following case

In [19]:
def eggs(cheese):
    cheese.append('hello')

some = [1,2,3]
eggs(some)

print(some)
[1, 2, 3, 'hello']


deepcopy() function in the copy module

Creating a separate list by following method.

In [20]:
import copy


some = [1,2,3,4]
cheese = copy.deepcopy(some)
In [21]:
cheese
Out[21]:
[1, 2, 3, 4]
In [22]:
cheese.append('hello')
In [23]:
cheese
Out[23]:
[1, 2, 3, 4, 'hello']
In [24]:
some
Out[24]:
[1, 2, 3, 4]

We here used the deepcopy() function of the copy module, which creates a new list in memory.



Sometimes when we are running out of line in the editor we can use \ in the end to tell python to ignore the next indentation.

In [25]:
print('Live long and' \
     + ' prosper')
Live long and prosper

Which is same as:

In [26]:
print('live long and prosper')
live long and prosper