DEV Community

PremPrema
PremPrema

Posted on

Day 20: Python String Immutability, format() & f-strings, and My First List

Hi 👋

I am Prem. I am learning Python in an online class with Muthu Sir (Payilagam). This is Day 20.

Today had three parts:

  1. String is immutable: what it means, and why Python does it.
  2. String formatting: format() with {} and f-strings.
  3. List: a new data type, indexing, range() and the for loop.

1. String is Immutable 🔒

Sir started by writing this in his class file:

String is Immutable:
Immutability: Non changeable
Enter fullscreen mode Exit fullscreen mode

Mutation: the COVID example 🦠

Sir explained the opposite word first. Mutable comes from mutation = changing. In COVID times we heard this word a lot: the virus changed from alpha to beta to gamma. That change is called mutation.

So immutable = it does not change.

The problem: "But it changed, Sir!"

Sir wrote this:

name = 'Eswari'
print(name)

name = 'Esvari'
print(name)
Enter fullscreen mode Exit fullscreen mode

Output:

Eswari
Esvari
Enter fullscreen mode Exit fullscreen mode

The value changed! So how can Sir say a string does not change? 🤔

Sir's answer: "Immutable in memory." The variable can point to a new value, but the old string in memory is never edited.

Every object has an ID (like Aadhar) 🪪

Sir wrote:

Object --> ID
Aadhar --> Unique Identification
Enter fullscreen mode Exit fullscreen mode

The government gives every person a unique Aadhar number. In the same way, every object we create in memory gets a unique ID. We can see it with the id() function.

On Sir's screen, print(id(name)) printed a big number like 138250666941552. (Your number will be different. It depends on your computer.)

Let me check if the ID changes when I "edit" the name:

name = 'Eswari'
first_id = id(name)
name = 'Esvari'
print(first_id == id(name))
Enter fullscreen mode Exit fullscreen mode

Guess the output before you open it 👇

Answer

False

The ID changed. Python did not edit 'Eswari'. It created a new memory for 'Esvari' and moved the name there.

Sir drew it on the board like this:

Step What happens in memory
name = 'Eswari' Box 1 holds 'Eswari'. name points to Box 1
name = 'Esvari' Box 1 is not touched. A new Box 2 holds 'Esvari'
After that name is disconnected from Box 1 and now points to Box 2

Sir's rule (from his notes):

If we try to edit an existing String content, that existing String content won't get changed. Instead, a new memory will be created and the edited / updated content will be added there.

Sir's mindset: when to ask WHY, when to ask HOW 🧠

A classmate asked a good question: "Sir, why does a string have immutability?"

Before answering, Sir gave us a learning rule. He wrote:

Conceptual: WHY
Advanced: HOW / WHAT
Programming Languages: Concept: OOPs, FP, WHY
React, Angular, Django, Springboot - WHAT / HOW
Enter fullscreen mode Exit fullscreen mode
What you study Question to ask
Concepts of a programming language (OOPs, Functional Programming) WHY
Frameworks and libraries (React, Angular, Django, Spring Boot, MVC/MVT architecture) HOW / WHAT

At the advanced level, if you keep asking "why" for everything, you get stuck. And if a question is out of the syllabus, don't make it your main question. You can search for it yourself.

Why is immutability needed? The 8 PM class story 🕗

Sir said: immutability is given to data types that are used very frequently. String is used everywhere: a name, a course, a place.

Story: Sir asks people, "What do you study at 8 o'clock at night?" The first person says Python. The second says Python. The third, fourth... 20 or 30 people all say Python.

Do we need 30 objects for the same word 'python'? No. Create one object and let everyone point to it. That is memory saving.

Another example from Sir: when lakhs of couriers or speed posts are sent to "Chennai, Tamil Nadu", the system should not store "Chennai, Tamil Nadu" one lakh times. Reuse the same memory. Same idea for country capital, PIN code, nationality, state and district names.

Can we prove it? Yes, with id():

course_name1 = 'python'
course_name2 = 'python'
course_name3 = 'python'
print(id(course_name1) == id(course_name2) == id(course_name3))
Enter fullscreen mode Exit fullscreen mode

Guess the output

True

All three names point to the same 'python' object in memory. Sir printed the three IDs separately and all were the same number.

But what if one person changes? 🔄

Now one person says: "Sir, I am not studying Python. I am studying JavaScript."

If Python edited the shared 'python' object, everyone's course would become JavaScript! That is wrong.

So Python disconnects only that person and gives him a new memory:

course_name1 = 'python'
course_name2 = 'python'
course_name3 = 'python'

course_name1 = 'JavaScript'
print(id(course_name1) == id(course_name2))
print(id(course_name2) == id(course_name3))
print(course_name1, course_name2)
Enter fullscreen mode Exit fullscreen mode

Guess the output

False
True
JavaScript python

Only course_name1 got a new ID. The others keep the same address. Sir's result: "The first one is different, remaining same."

👉 This is the reason for immutability: many names can safely share one object, because nobody can change it.


2. String Formatting with format() ✍️

Sir said that while learning strings, we should also know the formatting structure.

name = 'Raja'
degree = 'BTech'
print("{0} has completed {1}".format(name,degree))
Enter fullscreen mode Exit fullscreen mode

Output:

Raja has completed BTech
Enter fullscreen mode Exit fullscreen mode

Sir first forgot the quotes around the text and got an error 😄. Small mistake, then he added the double quotes and it worked.

The flower braces {} = Replacement Operator

The {} are called the replacement operator. format() is a method of the string. We give it two arguments, and they replace {0} and {1}.

A classmate asked: "Sir, is it like concatenation?" Sir: No, it is the replacement operator.

Guess the output experiments 🧪

Classmates asked: "Do I have to give only 0 and 1?" So Sir tried many changes, one at a time:

name = 'Raja'
degree = 'BTech'
print("{0} has completed {1}".format(name,degree))
print("{} has completed {} in the year {}".format(name,degree, '2026'))
print("{1} has completed {0}".format(name,degree))
print("{a} has completed {b}".format(a=name,b=degree))
Enter fullscreen mode Exit fullscreen mode

Guess the output

Raja has completed BTech
Raja has completed BTech in the year 2026
BTech has completed Raja
Raja has completed BTech

Change What happened Why
Empty {} Works, fills in order Python counts automatically
{1} ... {0} Name and degree swapped Numbers are positions of the arguments
{a} ... {b} with a=name, b=degree Works You can give any name instead of numbers
{5} ... {6} Error There are only 2 arguments (position 0 and 1)
Mix {0} and {} Error Use numbers everywhere or nowhere

The {5} error looked like this:

IndexError: Replacement index 5 out of range for positional args tuple
Enter fullscreen mode Exit fullscreen mode

Sir explained "positional arguments": each argument sits in its own position. Position 5 does not exist.

When we mix {0} and {}:

ValueError: cannot switch from manual field specification to automatic field numbering
Enter fullscreen mode Exit fullscreen mode

Sir: "If you don't give a number, don't give it anywhere." Otherwise Python gets confused.

Sir also said string format is used in many places, for example when we work with a database.

f-strings (the short way) ⚡

name = 'Raja'
print(f'My name is {name}')
Enter fullscreen mode Exit fullscreen mode

Output:

My name is Raja
Enter fullscreen mode Exit fullscreen mode

Put f before the quotes and write the variable directly inside {}.

Petrol price with 2 decimals ⛽

Sir asked: "After the point, how many digits do you want?" We said: two.

petrol_price = 107.35432
print(f"Today's price: {petrol_price:.2f}")
Enter fullscreen mode Exit fullscreen mode

Guess the output

Today's price: 107.35

.2f means: show it as a float with 2 digits after the point.


3. List 🛒

The problem: many items, one name

Sir asked: what is a list? Think of a grocery list. When we go to the shop, we write all items in one list: tomato, bread, chocolate...

Sir wrote:

List:
Grocery List:
Individual Objects into a single entity
Enter fullscreen mode Exit fullscreen mode

A list groups many separate objects into one object.

Now a candidate's details: name, age, Indian (True/False), height 175 cm, weight 72.3 kg. Different data types, but all about one person:

candidate = ['raja', 25, False, 175, 72.3]
print(candidate)
Enter fullscreen mode Exit fullscreen mode

Output:

['raja', 25, False, 175, 72.3]
Enter fullscreen mode Exit fullscreen mode

A list is written in square brackets [ ].

Indexing (வரிசை) and Negative Indexing

Sir wrote the index numbers under each item as a comment:

candidate = ['raja', 25, False, 175, 72.3]
        #       0   1       2     3     4
print(candidate[0])
print(candidate[-1])
Enter fullscreen mode Exit fullscreen mode

Guess the output

raja
72.3

Index 0 is the first item. Index -1 is the last item (counting from the right side).

Then Sir asked us to try "wrong" indexes too:

print(candidate[100])
Enter fullscreen mode Exit fullscreen mode
IndexError: list index out of range
Enter fullscreen mode Exit fullscreen mode

candidate[-25] also gives the same error. The list has only 5 items. Sir commented those lines out after we saw the error.

Micro to Macro: print every item 🔁

Micro (by hand):

print(candidate[0])
print(candidate[1])
print(candidate[2])
print(candidate[3])
print(candidate[4])
Enter fullscreen mode Exit fullscreen mode

Pattern: only the index changes: 0, 1, 2, 3, 4. It starts at 0 and stops before the length of the list.

Algorithm in plain words:

  1. Start i at 0.
  2. While i is less than the number of items, print candidate[i].
  3. Add 1 to i. Repeat.

Macro (while loop):

candidate = ['raja', 25, False, 175, 72.3]
i = 0
while i < len(candidate):
    print(candidate[i])
    i+=1
Enter fullscreen mode Exit fullscreen mode

len(candidate) gives the number of items = 5.

Dry run:

i i < 5 ? prints
0 True raja
1 True 25
2 True False
3 True 175
4 True 72.3
5 False (loop stops)

Object inside an object 🎒

Sir asked: in real life, do we keep an object inside another object? Yes! He wrote:

Bag - Laptop, Note, Pen
Enter fullscreen mode Exit fullscreen mode

A bag is one object, and inside it there are other objects. A box can be inside another box. A list works the same way: we group objects and keep them in another object.


4. The for loop and range() 🔢

Sir said the for loop is very easy. First he showed the range() function:

for index in range(5):
    print(index, end=' ')
print()
for index in range(1, 5):
    print(index, end=' ')
print()
for index in range(2,10,3):
    print(index, end=' ')
print()
Enter fullscreen mode Exit fullscreen mode

end=' ' means: don't go to the next line, put a space instead. The empty print() moves to a new line.

Guess the output

0 1 2 3 4
1 2 3 4
2 5 8

range(start, stop, step)

Part Meaning
start the first number
stop the end. The stop number is excluded
step how much to jump each time

range(5) starts from 0 and comes up to 4.

Dry run of range(2,10,3):

index index less than 10? prints
2 Yes 2
5 Yes 5
8 Yes 8
11 No (stops)

Sir wrote #2 5 8 11 14 next to it to show the jumps, and then explained why only 2 5 8 came: 11 is past the stop.

Negative numbers puzzle ➖

Sir's notes had:

for index in range(-10,-1,-2):
    print(index, end=' ')
print()
Enter fullscreen mode Exit fullscreen mode

Guess the output

Nothing prints (just an empty line)!

From -10 we jump by -2, so we go to -12. That is moving away from -1. So the loop never starts.

So Sir changed the step to +2:

for index in range(-10,-1,2):
    print(index, end=' ')
print()
Enter fullscreen mode Exit fullscreen mode

Output:

-10 -8 -6 -4 -2
Enter fullscreen mode Exit fullscreen mode

Puzzle from Sir: I want -1 -3 -5 -7 -9. How do I change the range?

A classmate gave the answer: "Start with -1, stop with -10, step with -2." Sir said: Super!

for index in range(-1,-10,-2):
    print(index, end=' ')
print()
Enter fullscreen mode Exit fullscreen mode

Output:

-1 -3 -5 -7 -9
Enter fullscreen mode Exit fullscreen mode

for loop reads like English 📖

name = 'abcdefghij'
for letter in name:
    print(letter, end=' ')
Enter fullscreen mode Exit fullscreen mode

Output:

a b c d e f g h i j
Enter fullscreen mode Exit fullscreen mode

Sir said: read it like English: "For every letter present in my name, print those letters with a space." Instead of saying it in English, we write it like this.

Sir also mentioned that a string can be turned into a list with the list() function (we will discuss it more later):

print(list('Ajay'))
Enter fullscreen mode Exit fullscreen mode
['A', 'j', 'a', 'y']
Enter fullscreen mode Exit fullscreen mode

Grocery list with for 🧅🍅

l = ['onion', 'tomato', 'chocolate', 'bread', 123, 10.5, True]

for each_item in l:
    print(each_item, end=' ')
Enter fullscreen mode Exit fullscreen mode

Output:

onion tomato chocolate bread 123 10.5 True
Enter fullscreen mode Exit fullscreen mode

5. List vs Array 🤔

A classmate asked: "What is the difference between a list and an array?"

Sir opened the Python documentation. Other languages (like C) use arrays. Core Python gives us the list. Python has an array module, and third-party libraries like NumPy give powerful arrays for number work, but the normal data type we use is the list.

Sir wrote:

Fixed Memory Size
In advance, Memory size should be known
Enter fullscreen mode Exit fullscreen mode
Array (in other languages) Python list
Fixed memory size Can grow
You must know the size in advance No need
Usually one data type Can store mixed data types ('raja', 25, False, 72.3)

Sir also said each language defines words like "object" and "array" in its own way. For example, in JavaScript an object is a key-value pair. That is where JSON (JavaScript Object Notation) comes from.


6. type() inside a for loop 🔍

Sir asked: what function tells us the data type of an object? type(). Can we use it inside the loop? Let's try:

l = ['onion', 'tomato', 'chocolate', 'bread', 123, 10.5, True]

for each_item in l:
    print(type(each_item), each_item, end=' ')
Enter fullscreen mode Exit fullscreen mode

Output:

<class 'str'> onion <class 'str'> tomato <class 'str'> chocolate <class 'str'> bread <class 'int'> 123 <class 'float'> 10.5 <class 'bool'> True
Enter fullscreen mode Exit fullscreen mode

Now print only the strings:

l = ['onion', 'tomato', 'chocolate', 'bread', 123, 10.5, True]

for each_item in l:
    if type(each_item) == str:
        print(each_item, end=' ')
Enter fullscreen mode Exit fullscreen mode

Guess the output

onion tomato chocolate bread


7. Task from Sir 📝

Sir's question at the end: from the list, print only the **float* value.* Use type(each_item) == float.

My answer

Change str to float in the if condition. The output is 10.5

Sir said we will continue the list in tomorrow's session.


What I learned today ✅

  1. String is immutable in memory. "Editing" a string creates a new memory. Check with id().
  2. Why immutability: frequently used values (like 'python') can share one object and save memory. If one person changes, only he gets a new memory.
  3. Concepts → ask WHY. Frameworks → ask HOW / WHAT.
  4. {} is the replacement operator. format() uses positions or names. f-strings are shorter. :.2f gives 2 decimals.
  5. List = individual objects in a single entity. Index from 0, negative index from the end, range(start, stop, step) with stop excluded, and for reads like English.

Thank you, Muthu Sir! 🙏

Top comments (0)