DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

Python Day 20: String Immutability, Lists and For Loops

1. String Immutability

Immutability means something that cannot be changed.

In Python, strings are immutable. This means once a string is created, its content cannot be changed directly.

If we try to modify an existing string, Python creates a new string object instead of changing the original one.

Example

name = 'Eswari'

print(name)
print(id(name))

name = 'Esvari'

print(name)
print(id(name))
Enter fullscreen mode Exit fullscreen mode
Output: 
Eswari
138682602342032
Esvari
138682602353408

Enter fullscreen mode Exit fullscreen mode

Here:

  • Initially, name refers to the string 'Eswari'.
  • Later, we assign 'Esvari' to the same variable.
  • Python creates or uses another string object.
  • The original string 'Eswari' is not modified.

The id() function helps us identify an object's identity during program execution.

Example 2: Assigning the Same String to Multiple Variables

course_name1 = 'python'
print(id(course_name1))

course_name2 = 'python'
print(id(course_name2))

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

Python may reuse the same string object for identical string values. Therefore, these variables may display the same ID.

Why is Immutability Needed?

Strings are frequently used in Python programs. Making strings immutable provides some useful benefits:

  • Safety: String content cannot be accidentally modified.
  • Memory optimization: Python can reuse certain string objects.
  • Reliability: String values remain unchanged after creation.
  • Hashing: Strings can be used as dictionary keys because they are immutable.

2. String Formatting

String formatting helps us insert variable values into a sentence.

Python provides different ways to format strings.

Using format() with Index Positions


name = 'Raja'
degree = 'BTech'

print("{0} has completed {1}".format(name, degree))
print("{} has completed {}".format(name, degree))
print("{} has completed {} in the year {}".format(name, degree, '2026'))
Enter fullscreen mode Exit fullscreen mode
Output:
Raja has completed BTech
Raja has completed BTech
Raja has completed BTech in the year 2026
Enter fullscreen mode Exit fullscreen mode
  • {0} refers to the first argument.
  • {1} refers to the second argument.
  • {} uses the arguments in order.

We can also change the order using index positions:


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

Using Named Placeholders

We can use names instead of index positions.

name = 'Raja'
degree = 'BTech'

print("{a} has completed {b}".format(a=name, b=degree))
Enter fullscreen mode Exit fullscreen mode
Output:
Raja has completed BTech
Enter fullscreen mode Exit fullscreen mode

Using f-Strings

An f-string is a simple and readable way to insert variables into a string.

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

We can also control decimal places.

petrol_price = 107.35432

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

Here, .2f displays the number with two digits after the decimal point.

3. Lists in Python

Imagine going to a grocery shop. Instead of storing each grocery item separately, we can keep all the items together in one list.

For example:

  • Tomato
  • Bread
  • Chocolate
  • Onion

A List is a collection that stores multiple items in a single variable.

In Python, we create a list using square brackets [].

Creating a List

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 Python list can store different data types, such as:

  • Strings
  • Integers
  • Boolean values
  • Floating-point numbers

4. List Indexing

Indexing means accessing an individual element using its position.

In Python, indexing starts from 0.

candidate = ['raja', 25, False, 175, 72.3]


print(candidate[0])
print(candidate[1])
print(candidate[2])
print(candidate[3])
print(candidate[4])
Enter fullscreen mode Exit fullscreen mode
Output:
raja
25
False
175
72.3
Enter fullscreen mode Exit fullscreen mode

Negative Indexing

Python also supports negative indexing.

Negative indexing starts from the end of the list.

Example:

candidate = ['raja', 25, False, 175, 72.3]

print(candidate[-1])
print(candidate[-2])
Enter fullscreen mode Exit fullscreen mode
Output:
72.3
175
Enter fullscreen mode Exit fullscreen mode

If we try to access an index that does not exist, Python raises an IndexError.

5. Accessing List Elements Using a While Loop

We can use a while loop to access every element in a list.

candidate = ['raja', 25, False, 175, 72.3]

i = 0

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

Here:

  • len(candidate) returns the number of elements.
  • i represents the current index.
  • candidate[i] accesses the element at that index.
  • i += 1 moves to the next index.

6. Understanding the range() Function

The range() function generates a sequence of numbers. It is commonly used with for loops.

It supports three arguments:
range(start, stop, step)

  • start: Starting value (included).
  • stop: Ending value (excluded).
  • step: Difference between values.

Example 1: range(5)

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

The default starting value is 0.

Example 2: range(1, 5)

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

Example 3: range(2, 10, 3)

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

Here, the step value is 3.

Example 4: Negative Step Values

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

A negative step value generates numbers in descending order.

7. Iterating Through a String Using a For Loop

A string is a sequence of characters.

We can use a for loop to access each character without manually using indexes.

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

Here, the for loop takes one character at a time from the string.

8. Iterating Through a List Using a For Loop

We can use a for loop to access each element directly.

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

for each_item in l:
    print(type(each_item), each_item)
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

Here, each_item receives one element at a time.

Printing Only String Values

We can use an if condition inside the for loop to filter specific data types.

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
Output:
onion tomato chocolate bread
Enter fullscreen mode Exit fullscreen mode

The condition checks whether each element is a string. Only string values are printed.

Top comments (0)