python
Unlocking Python: A Beginner's Guide to Variables and Data Types

Python is an interpreted language, meaning it processes code line by line, converting it into bytecode and executing it immediately. This differs from compiled languages, which read the entire code, convert it into bytecode, and execute it all at once. Python code execution is handled by the Python Virtual Machine, with popular environments including VS Code, PyCharm, and Jupyter etc.
Variables and Datatypes:
Variable is placeholder which is used to store data that can be referenced and manipulated during program execution. Unlike Java, C and many other languages, python variable don’t require explicit declaration of type. But there are some rules for creating variable :-
Variable names can only contain digits, letters, and an underscore(_).
It must start with a letter(A, B, C, a, b, c…) or underscore(_).
It is case-sensitive, like age and Age are two different variables.
It cannot be a Python keyword like if, else, for, print, class, etc.
Datatypes:
Datatypes refer to the type of data you have stored in a variable, like int, float, string, etc which determine what kind of operation can be performed. Since everything in python is object , so python datatypes are classes and variables are instances(objects) of these classes.
There are built-in datatypes in python are :-
Numeric
(i) int: It contains +ve and _ve whole numbers from -ve infinity to +infinity, and it’s value are represented by the int class.
(ii) float: It contains a decimal number and is represented by the float class.
(ii)complex: It is a combination of a real value plus an imaginary number, like 6 + 5j.
Sequence Type:
A. String: It is used to store anything, literally anything that is available on your keyboard, which is represented by the str class. It is created using single quotes(‘‘), double(““) or triple quotes(“‘ “‘).
It is immutable. If we need to manipulate strings, then we can use methods like concatenation, slicing, or formatting to create new strings based on the original. You should also know it takes more space than other datatypes because strings store every character with their own unicode( each character represented by standardized numeric code defined by unicode standard like ‘A’ —>U+0041).
Properties:
(i) Built-in methods:
capitalize(): Converts the first character to uppercase and the rest to lowercase.lower(): Converts all uppercase characters in a string to lowercase.upper(): Converts all lowercase characters in a string to uppercase.swapcase(): Swaps cases, converting lowercase to uppercase and vice versa.title(): Converts the first character of each word to uppercase.count(sub): Returns the number of times a specified substringsuboccurs in the string.find(sub): Searches for thesuband returns the index of the first occurrence where it is found, or -1 if not found.strip(): Removes leading and trailing whitespace (or specified characters).index(sub): Likefind(), but raises aValueErrorIf the substring is not found.replace(old, new): Returns a new string with all occurrences of theoldsubstring replaced by thenewsubstringjoin(iterable): The join() method is used to combine elements of an iterable into a single string, placing a chosen separator between each element.a = (‘a’, ‘b’, ‘c’)
print("-".join(a)) ——> “a-b-c”
(ii) Built-in functions:
len(string): Returns the length (number of characters) of the strings.str(object): Returns a string version of the given object
B. List: List are built-in data structure that stores an ordered collection of items. It is mutable, allows duplicate values, allow heterogeneous items. It is created using square brackets [] or using the list () constructor that needs passing an iterable (like a tuple, a string, or another list) to the list() function.
In Python, a list doesn’t store actual values directly. Instead, it stores references (pointers) to objects in memory. This means numbers, strings, and booleans are separate objects in memory and the list just keeps their addresses.
listOne = [‘a’ , 1, ,2 ,2.4 , ‘hello’, True , print()]
listTwo = list((‘a’ , ‘Hello’ , 2 , 2.5 ))
We can also create list by repeated elements using *.
listThree = [2] * 5 ——> [2,2,2,2,2]
Properties of list:(i) You can access list items by index. List starts at 0 index, so list[0] gives the first element, and it also allows -ve indexing, list[-1] will give the last element.
(ii) Slicing: You can extract a portion of items from list like list[first index , last index , step]
a[1 : 10 :1] , a[: :2], a[:5:]
(iii) Built-in methods:
append() - It will insert data at the end of the list ( a.append(5) ).
insert() - It will add data at specific position ( a.insert(index , value) for example a.insert(0,’a’)).
extend() - It is used to add multiple items to the end of a list at once (a.extend([ 1,2,3])
clear() - removes all items from a list (a.clear())
removes() - it will remove the first occurrence of an element (a.remove(‘a’))
pop() - Removes the element at a specific index or the last element if no index is specified.
count() - count the occurrence of item (count(item) )
index() -Returns the index of the first occurrence of a specified element ( index(item) ).
reverse() - reverse the list item
sort() - sort list items in ascending order
(iv) Built-in functions:
len(list) - Returns the number of items in a list.
max(list) - Returns the largest item from a list.
min(list)- Returns the smallest item from a list.
sum(list) - Returns the sum of all numerical items in a list.
list(iterable) - Converts other iterables (like tuples, strings, or sets) into a list.
enumerate() - enumerate(a) provides both the index (i) and the element (name) during iteration
and returns a list of tuples like [(0, 'a '), (1, 'b'), (2, 'c')] from enumerate([‘a’,’b’,’c’])
(v) List Comprehension: List comprehension is a concise and powerful way to create new lists by applying an expression to each item in an existing iterable (like a list, tuple, or range). It helps you write clean, readable, and efficient code compared to traditional loops. New lists can also be created by for loops, but it take multiples lines of code, whereas list comprehension takes one line.
a = [1, 2, 3, 4, 5 ]
list_comp = [val ** 2 for val in a ]
print(list_comp) ———> [1, 4, 9, 16, 25]
(vi) List unpacking: List unpacking in Python is a feature that lets you assign the elements of a List or tuple or any other iterable object to multiple variables in a single statement
a, b, c = [1,2,3] then a—>1, b—>2, c—>3
C. Tuples: A tuple in Python is an ordered, immutable (unchangeable) collection of items, which can be of any data type. Tuples are defined by enclosing elements in parentheses
()and separating them with commas. All the methods, function will work in a tuple as was in list. A tuple can also be sliced as a list or string. List and Tuple are same data structure but tuple is immutable .
3 Set Datatype:
1. Set: A set in python is unique, unordered(it means it doesn’t of index value), and mutable collection of items which can store different datatypes like strings, numbers, tuple but not everything. You cannot have duplicate value in set. It is created using {} and it is not itterable.
Each value in a set is stored via hashing function. The hash is used as an index to store the elements of set. Since hashing doesn’t maintain order, sets are unordered. Only immutable objects like numbers, strings, tuples are allowed in set. Mutable objects like list and dictionaries are not allowed.
Properties:
(i)Set Traversing:
A set cannot be traversed using index values cause it is unordered and it has no index.
(ii)Mathematical operation:
| Method | Description | ||
union(*others)/ ‘ | ` | print(a | b) |
intersection(*others) / & | Common elements - print( a & b) | ||
difference(*others) / - | Elements in first set but not others - print( a -b ) | ||
symmetric_difference(other) / ^ | Elements in either set but not both print( a ^ b) |
(ii) Built-in methods:
| Method | Description |
add(elem) | Adds a single element |
update(iterable) | Adds multiple elements from iterable |
discard(elem) | Removes element if present; no error if missing |
pop() | Removes and returns an arbitrary element |
isdisjoint(other) | Checks if no elements in common |
issubset(other) | Checks if all elements are in other |
issuperset(other) | Checks if contains all elements of other |
| clear() | Removes all element from set |
(iv) Built -n functio
| Function | Purpose |
len(set) | Number of elements |
min(set) / max(set) | Smallest / largest element |
sum(set) | Sum of elements |
sorted(set) | Returns sorted list |
all(set) | Returns true if all the elements of set are truthy otherwise false |
any(set) | Return True if at least one element is Truthy otherwise false |
- Frozenset : A frozenset in Python is a built-in data type that is similar to a set but with one key difference that is immutability. This means that once a frozenset is created, we cannot modify its elements that is we cannot add, remove or change any items in it. Like regular sets, a frozenset cannot contain duplicate elements.
- Mapping Type: Dict
A Python dictionary is a data structure that stores data in key-value pairs, where each key is unique and is used to retrieve its associated value. It is mainly used when you want to store and access data by a name (key) instead of by position like in a list. It is mutable, duplicates (key must be unique, but you can have duplicates in values), Order (follows insertion order it means value will be based on your key) and heterogeneous.
A dictionary is created by writing key-value pairs inside { }, where each key is connected to a value using colon (:). A dictionary can also be created using the dict() function.
d1 = {1:’a’ , 2:’b’ , 3:’c’} , d2 = dict(1:’a’ , 2:’b’ , 3:’c’)
A value in a dictionary is accessed by using its key. This can be done either with square brackets [ ] or with the get() method. Both return the value linked to the given key
(i) Built-in methods:
| Method | Description |
dict.keys() | Returns all keys |
dict.values() | Returns all values |
dict.items() | Returns key-value pairs as tuples |
dict.get(key, default) | Returns value for key, or default if not found |
dict.update(other_dict) | Updates dictionary with another dictionary |
dict.pop(key, default) | Removes key and returns its value |
dict.popitem() | Removes and returns the last inserted key-value pair |
dict.clear() | Removes all items |
dict.copy() | Returns a shallow copy |
dict.setdefault(key, default) | Returns value if key exists, else inserts key with default value |



