Python Notes: Strings, Lists, Loops
1. What is a String?
- A string is a datatype, written as
strin Python. - It is a collection of characters: alphabets, special characters and numbers.
- It is written in single or double quotes. Use triple quotes (
'''or""") for multiline text. - It is index based. Indexing starts from 0.
- Negative indexing runs right to left: the last letter is
-1. - Slicing syntax is
s[start:stop:step]. Thestopindex is not included.
s = 'python' print(s[0:3]) # pyt print(s[::2]) # pto print(s[::-1]) # nohtyp 2. Why are Strings immutable?
A string cannot be changed in place after it is created. Every "change" creates a new string.
s = 'raja' s[0] = 'R' # TypeError s = 'R' + s[1:] # new string 'Raja' Reasons:
- Safe sharing: many variables can point to the same string without one changing it for the others.
- Hashable: strings can be dictionary keys and set items.
- Speed and memory: Python can reuse identical strings.
3. .format() method
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)) Output:
Raja has completed BTech Raja has completed BTech in the year 2026 BTech has completed Raja Raja has completed BTech 4. What is a List?
- A list is an ordered, mutable collection written in square brackets
[]. - It can hold mixed types and duplicates.
- It is index based, like a string.
- Unlike a string, its items can be changed.
candidate = ['raja', 25, False] candidate[1] = 26 # allowed candidate.append(175) # add at the end 5. len() and list()
len() returns the number of items.
candidate = ['raja', 25, False, 175, 72.3] # 0 1 2 3 4 i = 0 while i < len(candidate): print(candidate[i]) i += 1 list() converts something into a list.
print(list()) # [] print(list('abc')) # ['a', 'b', 'c'] print(list(range(5))) # [0, 1, 2, 3, 4] print(list((1, 2, 3))) # [1, 2, 3] print(list(range(2, 10, 3))) # [2, 5, 8] 6. for loop with range
range(start, stop, step) stops before stop. The default start is 0 and the default step is 1.
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() for index in range(-1, -10, -2): print(index, end=' ') print() Output:
0 1 2 3 4 1 2 3 4 2 5 8 -1 -3 -5 -7 -9 A negative step only works when start is greater than stop.
