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))
Output:
Eswari
138682602342032
Esvari
138682602353408
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))
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'))
Output:
Raja has completed BTech
Raja has completed BTech
Raja has completed BTech in the year 2026
- {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))
Output:
BTech has completed Raja
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))
Output:
Raja has completed BTech
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}')
Output:
My name is Raja
We can also control decimal places.
petrol_price = 107.35432
print(f"Today's price: {petrol_price:.2f}")
Output:
Today's price: 107.35
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)
Output:
['raja', 25, False, 175, 72.3]
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])
Output:
raja
25
False
175
72.3
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])
Output:
72.3
175
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
Output:
raja
25
False
175
72.3
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=' ')
Output:
0 1 2 3 4
The default starting value is 0.
Example 2: range(1, 5)
for index in range(1, 5):
print(index, end=' ')
Output:
1 2 3 4
Example 3: range(2, 10, 3)
for index in range(2, 10, 3):
print(index, end=' ')
Output:
2 5 8
Here, the step value is 3.
Example 4: Negative Step Values
for index in range(-1, -10, -2):
print(index, end=' ')
Output:
-1 -3 -5 -7 -9
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=' ')
Output:
a b c d e f g h i j
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)
Output:
<class 'str'> onion
<class 'str'> tomato
<class 'str'> chocolate
<class 'str'> bread
<class 'int'> 123
<class 'float'> 10.5
<class 'bool'> True
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=' ')
Output:
onion tomato chocolate bread
The condition checks whether each element is a string. Only string values are printed.
Top comments (0)