0% found this document useful (0 votes)
3 views4 pages

Python Basics

The document provides an overview of Python data types, including built-in types such as int, float, str, bool, list, tuple, set, and dict, along with their characteristics and examples. It explains the difference between mutable and immutable types, type conversion, and common operations on lists and strings. Additionally, it emphasizes the importance of understanding data types for efficient coding and includes practical examples and methods for manipulating lists and strings.

Uploaded by

karthika
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Python Basics

The document provides an overview of Python data types, including built-in types such as int, float, str, bool, list, tuple, set, and dict, along with their characteristics and examples. It explains the difference between mutable and immutable types, type conversion, and common operations on lists and strings. Additionally, it emphasizes the importance of understanding data types for efficient coding and includes practical examples and methods for manipulating lists and strings.

Uploaded by

karthika
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON DATA TYPES Example

What is a Data Type? x 10 → int


A data type specifles the type of value a variable can hold. y
3.14 → float

It determines the kind of operations that can be performed on that value. name "Sagar" → str
flag = True → bool

1. Built-in Data Types in Python 2. Mutable vs Immutable


Data Type Description Example Type() Output
Mutable (can be changed)
Integer numbers x 25
int <class int'> • list
(positive or negative whole numbers) y-10 dict
Decimal numbers pi 3.14 set
float temp -0.5
<class 'float'>
(numbers with a decimal point)
Sequence of characters name "Sagar" Immutable (cannot be changed)
str (text enclosed in quotes) city 'Delhi'
<class 'str'>
int
float
Boolean alues is_active True
bool (True or False)
<class 'bool' > str
is_done False
tuple
list Ordered, mutable collection nums [1, 2, 3] <class 'lst'> • bool
(items in square brackets) names ("a, "6)
Ordered, immutable collection t (1, 2, 3) 3. Checking Data Type
tuple (items in parentheses) days (" Mon', Tue") <class "tuple'>
x 10

Unordered collection of s (1, 2, 3) print(type(x)) # <class 'int'>


set <class 'set'> y 3.14
unique items (curly braces) letters ('a, B)
print(type(y)) # <class 'float">
dict Collection of key-valu pairs info (name: "Sagar". <class 'dict'> name "Sagar"
(eurly braces with key:value) "age": 21) print(type (name) ) # <class 'str'>
4. Examples with Output
print(type (a)) <class 'int'>
a 10 # int
f (1, 2, 3) print (type(b)) <class 'float'>
<class 'str>
b 2.5 # float (1, 2, 3) print(type(c))
9 print(type (d)) → <class 'bo01'>
C "Hello Python" str
h {"name": "Sagar", "age": 21) print(type(e)) → <class 'list'>
d - True # bool print(type (f) ) → <class 'tuple'>
e (1, 2, 3] # list print(type (g) ) → <class 'set'>
print(type (h)) <class 'dict'>

5. Type Conversion (Type Casting) 6. Key Takeaways


Convert one data type to another using built- in functions. * Every value in Python has a data type.
Common functions: int(), float(), str(), bool(), list(). tuple(), set(), dict() t Use type() to check the data type of any value.
* Mutable types can be changed, immutable cannot.
"10" int(x) 10 float (x) → 10.0 bool(*) + True
* Choosing the right data type helps write efficient code.

* Good Practice: Uhderstand the data type and use it wisely to avoid errors and write better programs. @[Link]
: PYTHON LIST
Page - 17
List s one of
the most
inportant built-in
data type n
A List is an ordered collection of items.
Python.
Items can be of any data type (int, float, str, bool, etc.)
Lists are mutable, meaning we can change, add or remove items after creation.

1. Creating a List 2. Accessing Elements


Lst [) # empty list Example List:
nums (1, 2, 3, 4) Lst (10, 20, 30, 40, 50]
# ist of integers • Lst[0] → 10 (first element)
names ("Aman", "Riya", "Karan"] # list of strings index 3
• Lst[2] → 30
mixed [1, "Hello", 3.5, True) #mixed list 10 20 30 40 50 . Lst[-1) → 50 (last element)

• Lists can contain duplicate values. negative


indes
-5 -4 -3 -2 -1 . Lst[-3] 30

3. Basic Operations 4. List Slicing 5. Useful List Methods


Change Ita Lst (10, 20, 30, 40, 50] [Link](x) → add * al the end
Lst[1] 25 [10, 25, 30, 40, s0)
• Lst[1:4) + [20, 30, 40] Lst. insert(i, x) insert * at index i
Add Itam (append) [Link] (iter) add all itemu of lter at end
Lst. append (60) # [10, 25, 30, 40, 50, 60) Lst[:3) [10. 20. 301
Lst. remove (x) → remove first occurrenca of x
Insert Item • Lst[2:] [30, 40, 50)
Lst. pop() remove & return item at index i
[Link](2, 99) #(10, 25, 99, 30, 40, 50, 60) Lst(::2) [10, 30, 50) Lst. index(*) → return index of first occurrenca
Ramove Itam (by value)
Lst. remove (25) # removes first oceurrence of 25
. Lstl::-1) [50, 40, 30, 20, 10) [Link] (x) return count of x
Remove Itam (by indax) [Link]() • sort the list (ascending)
[Link](2) #removes item at index 2 (99) Syntax [Link] () reverse the list
Clear Lst Lst[start : stop step]
• start starting index (inclusive) [Link]() + return a shallow copy of list
[Link]() Len(Lst) + return number of items in lis
• Delata List • stop → ending index (exclusive)
del Lst # list is deleted • stap interval/step size (default 1)

6. List Operations 7. List Comprehension 8. Important Points


• Concatenation (+) Create a nw list in a simple and clean way. V List is ordared and indexed.
[1, 2]
b [3, 4] • Squares of nmbers 1 to 5 Allows duplicate values.
#[1, 2, 3, 4] squares [x**2 for x in range(1, 6)) Mutable (changes can be mada).
# (1, 4, 9, 16, 25)
•Repetition () U Heterogeneous (can store different data types).
(1, 2] • Even numbers from 1 to 10
Lists are dynamic in size.
3 #[1, 2, 1, 2, 1, 2] evens (x for x in range(1, 11) if * 2 0]
# [2, 4, 6, 8, 10]
•Membership (in / not in)
• From existing list
Tip:
2 in a # True Use lists when you naed an ordered
5 not in a # True nums [1, 2, 3, 4)
cube [***3 for x in nums] # (1, 8, 27, 64] collection that can change over time.

9. Real Life Examples ★ Good Practice


Studant Marks HHP Skopping Cart To-Do List D Scores in a Game Practice more with lists to
[85, 92, 78, 90) ('pen', 'book', "bag'] ('tady'. 'eercise', 'code'] (120, 150, 100, 180) become a better progravner!
Page - 18
A String in Python
is a sequence of
characters enclosed
PYTHON STRING
(' ') Strings ane immutable (cannot be changed after ereation).
in single quotes ( "). "Hello"
or double quotes It can contain letters, diqits, spaces and special characters.
Indexing starts from 0.
1. Creating Strings 2.. Indexing and Slicing
• s[0] →P # first character
s1 "Hello World" #using double quotes
s "Python"
s(3)
Index 1 2 • s[-1) → 'n' # last character
s2 'Python is fun' #using single quotes
s[1:4) → 'yth' # from index 1
t to 3 (exclusive)
s3 = 'Multi # using triple quotes
Line
s[2:] → 'thon" # from index 2 till end
Negative -5 -4 -3 -2 -1
Index s[:4] → 'Pyth # from start to
String' index 3

3. String Operations 4. Useful String Methods 5. String Formatting


Concatanation ( ) s. upper() convert to upparcass
s. lower() → convert lo loercase
• Using f-string (Python 3.6+)
a. "Hello" * • "Python" # "Hello Python" name "Sagar
[Link]() first letter of cach ord capital
Repetilion () age 21
[Link]() first character capilal
b -* 5
[Link]() remove spaces from both ends mag fMy name is (name) and I an (age) years otd."
Mambership ( in s. LstripO remove spaces fromn left
# True [Link]( ) remove spaces from right • Using format()
"Py" in [Link](old, ntw) eplaca old ith ne
Java' not in a # True msg "My name is () and I am ) years old."format(nams, age)
[Link](sep) lt sring by separalor (defou pace)
Length ( len()) 1. jein(iterable) → jin elemenls th string as sparator Using % operator
len("Python") #6 [Link](sub) return indez of first occurrence
(-1 f not found) mag "My name is %s and I am td years dd." % (name, age)
[Link](sub) counl total occurences of substring

6. Escape Sequences 7. String Imnutability 8. Raw String


Sequence Meaning Example: Strings camot be changed once ereated. Used to ignore escape charactars.
n Ne Line
s"Hello\nWelcome\tto Python . Any operalion creales ntring.
Tab
Example: Example:
print(s)
Backslash path r"C:\\Users\\Sagar\\Docunents"
Single Quote
Output: "hello"
print(path)
Hello\nkWelcome to Python s(0] 'H' X Error
Double Quote s "H • s(1:) creates new string -→ Hello' # Output: C:\\Users\\ Sagar\\Documents

9. Built- in Functions with Strings Example: 10. Important Points


Strings are imumutable.
lan(s) → length of string ord("A') → ASCII vae (65) s"python
→ smallest charactar chr(65) → chanscler from ASCII (A) print(len(s) #6 Ø Ihdexing starts from 0.
min(s)
print(min(s)) Supports slicing and many methods.
max(s) largest eharacter sorted(s) + return sorted lt
of characters print(sorted(s)) # ('h, 'n', '. 'p", , 'y) Can conlain any characters.
Ø Widaly used in real world applicalions.

Tip: Use strings to store and manipulate text data efficiently in your programs. SGood Practice: Practice more with strings to master taxt handling!
PYTHON TUPLE 3
Page - 19
Tugle is an
ordared collection
of items.
It is mmutable • Tuples are similar to lists but immutable.
(cannot be changed).
• Items can be of any data type (int, float, str, bool, ete.).
• Useful when data should not be changed.
1. Creating Tuples 2. Accessing Elements
t1 (10, 20, 30, 40) # tuple of integers t. (10, 20, 30, 40, 50) 10 # first element
t2 ('a', 'b', 'e') # tuple of strings • t[2] → 30
#mixed tuple Index 1 2 4
E3(1, "HelLlo', 3. 14, True) t[-1) → 50 # last element

# empty tuple 10 20 30 40 50 t[-3) 30 #fot


45 (5,) # single element tuple • t[1:4] 4 (20, 30, 40) slicing
Negative -5 -4 -3 -2
Index
• t[::-1] → (50, 40, 30, 20, 10) reverse

Note: For a single element, comma (,) is required.

3. Basic Operations 4. Tuple Slicing 5. Tuple Methods


• Length (len()) t. (10, 20, 30, 40, 50) Tuples have only two built -in methods:
returns number of items
len(t) t[1:4) (20, 30, 40)
(10, 20. 30) 1. count (x) → returns number of
• Membership (in / not in) e[:3)
occurrences of *
20 in t # True [2:) → (30, 40, 50)
2. index(x) returns index of frst
100 not in t # True t[::2) + (10, 30, 50)
t[::-1) (50, 40, 30, 20, 10) occurrence of
Concatenation (+)
t1 (1, 2) Syntax Exampls:
t2 (3, 4) tfstart : stop : step) t. (10, 20, 30, 20, 40, 20)
t t1 2 # (1, 2, 3, 4) start starting index (inclusive) [Link](20)
• Repetilion () stop → nding index (exclusive) t. index(30) # 2

t (1, 2) • 3 # (1, 2, 1, 2, 1, 2)
step interval/step size (default 1)
& Nate: If element not found, index() raises ValueError.

6. Immutability 7. Packing and Unpacking 8. Differences: List vs Tuple


Tuples are immutable. Once created, Packing (creating tuple) Feature List
Tuple
we canot change, add or renove items. t 1, 2, 3, 4 parenthesis optional Mutable ? Yes (can be changed) No (imutable)
t (1, 2, 3) print(t) # (1, 2, 3, 4)
t[O) 10 TupeError Syntax
Unpacking (assigning values to variables) Only count() and
However, if a tuple contains mutabla objects a, b, c, d t
Methods Many methods
index()
(ke lat), thess objects can be changed. print(a, b, G, d) # 1 2 3 4
Performance Slower Fastar
t (1, (10, 20), 3) Swapping two variables
t(1)[0) 10, 20 Mamory Usage Mere Less
99 # Allowed *, y
print(t) # (1, (99, 20), 3) Use Case When data needs Whan data should
print (*, y) # 20 10 not change not change

9. Real Life Examples 10. Key Takeaways


Coordinates Date Record Tuples are ordered and immutabla
O
point (10.5, 20.3) A99 date (2024, 5, 30) student ('Sagar', 21, 'CSE") E Ue tuples when data should not change.
Faster and memory fcient than lists.
# (x, y) position # (year, month, day) # (name, age, branch)
O Can contain duplicate values.

You might also like