0% found this document useful (0 votes)
7 views

Python Notes Day05

Python notes

Uploaded by

kalupranav2611
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Notes Day05

Python notes

Uploaded by

kalupranav2611
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Topics Covered:

1. Subscription:
– Indexing
– Slicing
– Assignment
2. Range Function/Object
3. Datatypes:
– Fundamental
– Derived
4. Mutability/Immutability
5. Obejct Initialization
6. String Interning

- Before Starting let's look into, what are the Fundamental and
Derived Datatypes we have in Python:
I) Literal / Fundamental Datatypes:
1. Integer
2. Float
3. Complex
4. Boolean
5. String
6. None

II) Literal COllections / Derived Datatypes


1. Lists
2. Tuples
3. Dictionaries
4. Sets
5. Frozen Sets
6. Range

.....etc......

---> Things to remember:


• All fundamental datatypes (including strings) are IMMUTABLE.
• Many but NOT ALL derived datatypes are mutable.
• Some derived datatypes like: Tuples and Frozen Sets have the property of being
IMMUTABLE.
### - Visual explaination of the concept mutability and
immutability in Python using an integer variable and a list.

Breakdown of the Concept:


1. Integer (a = 10) : Fundamental Datatype/Literal (IMMUTABLE)
• Initially, variable a is assigned the value 10.
• In Python, integers are immutable. This means that when we change the value of a to 20,
Python does not modify the existing memory space. Instead, it creates a new object in
memory for 20, and 'a' points to this new memory location.
• The image shows how a = 10 is stored at memid10, but when a = 20, it changes to a new
memory location memid20.
• When the referece count to 10 becomes zero the garbage collector will automatically
removes/erase that object.

2. List (lst1 = ['a', 1, 100, 10.2]) : Derived Datatype/Literal Collection (MUTABLE)


• Next, we have a list lst1 containing the elements 'a', 1, 100, and 10.2.
• Lists in Python are mutable, meaning we can change their content without creating a
new list object in memory.
• The image shows that the memory ID for lst1 remains the same (memidlst1), even if the
elements within the list change. The elements themselves point to different memory
locations (like memid100, memid10.2, etc.), but modifying the list doesn't change the
memory ID of lst1.

1. Subscription(Indexing)
• Indexing is a way to access individual elements within a sequence, such as list, tuple,
or string, Using their position (index) in that sequence.
1. Positive Indexing:
• Starts from 0 for the first element, 1 for the second, and so on.

# For example:
# indexing in a string
str1 = 'Apple'
print(str1[0]) # for accessing the first character of a string
print(str1[1]) # for accessing the seconds character of a string
print(str1[4]) # accessing the last character of a string

A
p
e

# indexing in list
lst1 = [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]
print(lst1[0]) # accessing the first element of list
print(lst1[3]) # accessing the fourth element of list
print(lst1[9]) # accessing the last element of list

101
104
110

2. Negative Indexing:
• Starts from -1 for the last element, -2 for the second last, and so on.
# For example:
str2 = 'Python'
print(str2[-1]) # accessing last character of string
print(str2[-2]) # accessing second last character of string

n
o

• What's the use of NEGATIVE INDEXING if we have positive indexing.


# String
str2 = 'Betty Bought Some Butter but the butter was bitter so betty
bought some better butter to make the bitter butter better!'
print(str2)
print('Last Character of String: ', str2[-1])

Betty Bought Some Butter but the butter was bitter so betty bought
some better butter to make the bitter butter better!
Last Character of String: !

# List
lst1 = list(range(101,200))
print(lst1)
print('Last Element of the List: ', lst1[-1])
[101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128,
129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156,
157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184,
185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198,
199]
Last Element of the List: 199

• In case we have very long values in a string or list accessing the characters/elements is
very difficult by positive indexing. In such cases we use NEGATIVE INDEXING.

Index Assignment :
• Index assignment is a powerful feature that allows you to manipulate data efficiently in
Python.
• Using index assignment we can modify the elements within sequences like lists.
• Note that you cannot perform index assignment on immutable objects like string, tuple
and sets.
# FOr example:
list1 = list(range(101, 111))
print(list1)
# Accessing the 4th index element
print('4th index element of list: ', list1[4])
# Modifying the 4th index element using index assignment
list1[4] = 501
print('After modifying: ', list1)

[101, 102, 103, 104, 105, 106, 107, 108, 109, 110]
4th index element of list: 105
After modifying: [101, 102, 103, 104, 501, 106, 107, 108, 109, 110]

print(list1)
# midifying the last element of the list by negative indexing
list1[-1] = 200
print(list1)

[101, 102, 103, 104, 501, 106, 107, 108, 109, 110]
[101, 102, 103, 104, 501, 106, 107, 108, 109, 200]

Slicing :
• Syntax for Slicing:
– Slicing in Python takes 3 parameters

– [Start index : Stop Index : Step Size]


– enclosed in Square Brackets next to the object that supports indexing.
• Slicing in Python is a technique used to access a portions of a sequences, such as a
strings, lists or tuples by specifying a range of indices.
• Remember that in SLICING and all other SYNTAX/FUNCTIONS that deal with a stop index
number - the stop index number is ALWAYS EXCLUSIVE.
• Suppose we have a string 'Data Science' and we want to extract only 'Data' from it using
slicing we will do [0:4] not [0:3] because stop index is always ECLUSIVE(not included).
• Let's see some Examples:
str1 = 'Python is a general purpose language'
print(str1)

Python is a general purpose language

# Now if i want to extract the word 'Python' from it


str1[0:6]

'Python'

# Extracting word 'general'


str1[12:19]

'general'

# Extracting last word


# using positive indexing
str1[28:]

'language'

# using negative indexing


str1[-8:]

'language'

Steps in Slicing
# For example:
abc = 'Python'
print(abc[0:6:1]) # 1 the dfault step size in python

Python

print(abc[0:6:2]) # step size 2 will take alternate character.

Pto

print(abc[0:6:3]) # After first character step size 3 will skip two


characters and take third one and so on.

Ph

print(abc[::-1]) # -1 step size will print the string in reverse


nohtyP

print(abc)
print(abc[-4::])

Python
thon

print(abc[-4::-1])

tyP

• start : stop : step


• If I leave one of the positions blank then what defaults does it take.
• ::
• Beginning of itereable : End of the Iterable : Default of positivve 1
• However, if the step size is defined in negative terms then this changes to :
• End of Iterable : beginning of Iterable : Negative Step

1. When Positive Indexing Step:


- First entry before colon if left empty means beginning of string.
- Second entry before colon if left empty means end of string.
- Third entry is default 1 if left empty.
- Beginning : End : Step
- Start : Stop : Step

2. When Negative Indexing step


- First entry before colon if left empty means end of string.
- Second Entry before colon if left empty means beginning of string.
- Third entry is default 1 if left empty (CANNOT be left blank if
negative step required)
- End:beginning:Step
- Start : Stop : Stepp : Step

str01 = 'I love to read books'


print(str01)
print(len(str01))
print(str01[-10:-5:1])

I love to read books


20
read

- Slice Assignment:
- Slice assignemnt in Python is a technique used to access and modify
a portions of a sequences, such as a lists, by specifying a rang of
indices.
# For example:
str1 = 'Sameer Shaikh'
str1[-6:]

'Shaikh'

str1[-6:] = 'Sharma'

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[38], line 1
----> 1 str1[-6:] = 'Sharma'

TypeError: 'str' object does not support item assignment

• here it doesn't work because strings are immutable.


# Let's try on lists
lst01 = list(range(101, 111))
print(lst01)

[101, 102, 103, 104, 105, 106, 107, 108, 109, 110]

lst01[4:7] = [205, 206, 207]


print(lst01)

[101, 102, 103, 104, 205, 206, 207, 108, 109, 110]

lst01[4:7] = [305, 306]


print(lst01)
print(len(lst01))

[101, 102, 103, 104, 305, 306]


6

--> Things to Remember:


• Slice assignment on lists in python - two rules
a. The number of elements BEING replaced do not have to match the number of
elements replacing them.
b. The values replacing the original values MUST be in an ITERABLE format(literal
collection)
[105,106,107] = [205,206]

[ 0 1 2 3 4 5 6 7 8 9]
[101,102,103,104,105,106,107,108,109,110]
[ 0 1 2 3 4 5 6 7 8]
[101,102,103,104,205,206,108,109,110]

• So according to rule 1, here if we assign only two elemetns instead of three, the two
elements list will take the place of that three elements and the index number will get
shift to the next element.
# Examples of rule no 2
# before understanding rule no. 2 practically let's see bit about
tuples.

# To create tuple
tupl1 = (1,2,3)
print(tupl1)
print(type(tupl1))

(1, 2, 3)
<class 'tuple'>

# we can also create tuple like this


tupl2 = 1,2,3
print(tupl2)
print(type(tupl2))

(1, 2, 3)
<class 'tuple'>

# Another way is
tupl3 = (1,) # single element tuple
print(tupl3)
print(type(tupl3))

(1,)
<class 'tuple'>

# Can we do this
tupl4 = (1)
print(tupl4)
print(type(tupl4))

1
<class 'int'>

• In above example it is not considered as tuple, single element inside parathesis without
comma(,) is not considered as tuple, It will be considered as an Integer.
# Now, understanding rule no. 2 practically
lst_01 = list(range(101,111))
print(lst_01)

[101, 102, 103, 104, 105, 106, 107, 108, 109, 110]
lst_01[4:7] = [205,206,207]
print(lst_01)

[101, 102, 103, 104, 205, 206, 207, 108, 109, 110]

• We can perform slice assignment like this on list, but


lst_01[4:7] = 205
print(lst_01)

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[58], line 1
----> 1 lst_01[4:7] = 205
2 print(lst_01)

TypeError: can only assign an iterable

• We cannot do this, because according to rule no. 2 the values replacing the original
values muwt be an Iterable.
• It should not be a litral instead literal collection.

You might also like