0% found this document useful (0 votes)
2 views

Python Revision Tour II Notes (1)

This document provides a comprehensive overview of Python data types including strings, lists, tuples, and dictionaries. It covers their characteristics, creation methods, operations, indexing, slicing, and commonly used functions and methods. Each section includes examples to illustrate the concepts effectively.

Uploaded by

KSHAMA RAUT
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Revision Tour II Notes (1)

This document provides a comprehensive overview of Python data types including strings, lists, tuples, and dictionaries. It covers their characteristics, creation methods, operations, indexing, slicing, and commonly used functions and methods. Each section includes examples to illustrate the concepts effectively.

Uploaded by

KSHAMA RAUT
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

CHAPTER 2: PYTHON REVISION TOUR II

STRING

1. Introduction to Strings

Strings in Python are sequences of characters enclosed in single, double, or triple quotes. Strings are
immutable, meaning they cannot be changed after they are created.

# Example of a string
s = "Hello, World!"

2. Traversing a String

Traversing a string means iterating through each character of the string. You can do this using a for loop
or by using indexing.

Example: Traversing using a for loop

s = "Hello"
for char in s:
print(char)

Output:

H
e
l
l
o

Example: Traversing using indexing

s = "Hello"
for i in range(len(s)):
print(s[i])

Output:

H
e
l
l
o
3. String Operators

Operator Description Example Output


+ Concatenation (joins two strings together) "Hello" + " World!" "Hello World!"
* Repetition (repeats the string multiple times) "Hello" * 3 "HelloHelloHello"
in Membership test (checks if substring exists) "World" in "Hello World!" True
Membership test (checks if substring doesn't "Python" not in "Hello
not in True
exist) World!"

4. String Slicing

String slicing allows you to extract a portion of a string. It uses the syntax: string[start:end:step].

Operation Description Example Output


s[start:end] Extract substring from start to end (exclusive) "Hello"[1:4] "ell"
s[:end] Extract from the beginning up to end (exclusive) "Hello"[:3] "Hel"
s[start:] Extract from start to the end "Hello"[2:] "llo"
s[start:end:step] Extract substring with step (skipping elements) "Hello"[::2] "Hlo"

5. String Functions and Methods

Method/Function Description Example Output


len(s) Returns the length of the string len("Hello") 5
Converts all characters in the string to
s.upper() "hello".upper() "HELLO"
uppercase
Converts all characters in the string to
s.lower() "HELLO".lower() "hello"
lowercase
s.capitalize() Capitalizes the first letter of the string "hello".capitalize() "Hello"
s.strip() Removes leading and trailing spaces " Hello ".strip() "Hello"
s.replace(old, Replaces occurrences of old with new "Hello World".replace("World", "Hello
new) in the string "Python") Python"
Splits the string at each occurrence of ['Hello',
s.split(delim) "Hello,World".split(",")
the delimiter delim 'World']
Returns the index of the first
s.find(sub) "Hello".find("l") 2
occurrence of sub, or -1 if not found
Joins all elements of the iterable with "Hello
s.join(iterable) " ".join(['Hello', 'World'])
the string as a separator World"
Returns True if the string contains
s.isdigit() "1234".isdigit() True
only digits
Returns True if the string contains
s.isalpha() "hello".isalpha() True
only alphabetic characters
Method/Function Description Example Output
Counts how many times sub occurs in
s.count(sub) "hello".count("l") 2
the string

Example Usage:
s = " Hello, World! "

# Strip spaces

print(s.strip()) # Output: "Hello, World!"

# Replace part of the string

print(s.replace("World", "Python")) # Output: " Hello, Python! "

# Split string into list

print(s.split(", ")) # Output: ['Hello', 'World!']


LIST
1. Characteristics of List

1. A list is a collection of items (elements) which are ordered and changeable.


2. Lists are mutable, meaning their contents can be changed after creation.
3. Lists can contain elements of different data types: integers, strings, floats, even other lists.
4. Lists are indexed, with the first element at index 0.
5. Defined using square brackets [].

Example:

my_list = [10, "Hello", 3.14, True]

2. Creation of List

You can create a list in various ways: #

Empty list
list1 = []

# List of integers list2


= [1, 2, 3, 4]

# Mixed data types


list3 = [1, "apple", 3.5, False]

# Nested list
list4 = [1, [2, 3], 4]
3. List Operations

Basic operations you can perform on lists:

Operation Example Result / Description


Concatenation [1, 2] + [3, 4] [1, 2, 3, 4]
Repetition [0] * 3 [0, 0, 0]
Membership 3 in [1, 2, 3] TRUE
Length len([1, 2, 3]) 3
Deletion del mylist[0] Deletes the 1st element

4. List Indexing

Accessing elements using their index (starting from 0):

List Indexing:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry (negative
indexing)

5. List Slicing

Extracting a part (sublist) from a list:

List Slicing:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[::2]) # [10, 30, 50]

6. Functions of List

Some commonly used list functions:

Function Description Example


len() Returns number of elements len([1,2,3]) → 3
max() Returns maximum element max([3,5,1]) → 5
min() Returns minimum element min([3,5,1]) → 1
sum() Returns sum of numeric list sum([1,2,3]) → 6
list() Converts another type (like string) into a list list("abc") → ['a', 'b', 'c']
7. List Methods

Common methods to manipulate lists:

List Methods in Python – With Explanation & Examples:

Method Explanation Example Output


append(x) Adds item x to the end of the list a = [1, 2] [1, 2, 3]
a.append(3)
insert(i, x) Inserts item x at position i a = [1, 3] [1, 2, 3]
a.insert(1, 2)
Adds all elements of lst to the end of the
extend(lst) a = [1, 2] [1, 2, 3, 4]
list
a.extend([3, 4])
remove(x) Removes the first occurrence of value x a = [1, 2, 3, 2] [1, 3, 2]
a.remove(2)

Removes and returns element at index i


pop(i) a = [1, 2, 3] Returns 3, list becomes [1, 2]
(default is last)
a.pop()
index(x) Returns the index of first occurrence of x a = [10, 20, 30] 1
a.index(20)
Returns number of times x appears in
count(x) a = [1, 2, 2, 3] 2
the list
a.count(2)
Sorts the list in ascending order
sort() a = [3, 1, 2] [1, 2, 3]
(modifies list)
a.sort()
reverse() Reverses the elements of the list a = [1, 2, 3] [3, 2, 1]
a.reverse()
clear() Removes all elements from the list a = [1, 2, 3] []
a.clear()
copy() Returns a shallow copy of the list a = [1, 2, 3] b = [1, 2, 3]
b = a.copy()
TUPLE
TUPLE

A tuple is an ordered collection of items, which is immutable (i.e., it cannot be changed after
creation). Tuples are similar to lists but use round brackets () instead of square brackets [].

CHARACTERISTICS OF TUPLE

1. Ordered – Elements are stored in a specific order.


2. Immutable – Once created, elements cannot be changed.
3. Allow duplicates – Tuples can contain repeated values.
4. Can hold different data types – Integers, strings, lists, etc.
5. Indexing – Elements can be accessed using indexes.
6. Faster than lists – Due to immutability.

CREATION OF TUPLE:

1. Empty Tuple
t = ()

2. Tuple with values


t = (1, 2, 3, 4)

3. Tuple without parentheses (not recommended)


t = 1, 2, 3

4. Single element tuple


t = (10,) # Comma is important

5. Nested Tuple
t = (1, 2, (3, 4), [5, 6])
Tuple Operations

Operation Example Description


Concatenation (1, 2) + (3, 4) Adds two tuples

Repetition (1, 2) * 3 Repeats the tuple multiple times

Membership 3 in (1, 2, 3) Checks if an element is in tuple


Length len((1, 2, 3)) Returns number of items

Tuple Indexing:

Just like strings and lists, tuple elements can be accessed using indexes.

t = (10, 20, 30, 40)


print(t[0]) # 10
print(t[-1]) # 40

Tuple Slicing:

You can extract parts of a tuple using slicing.

t = (10, 20, 30, 40, 50)


print(t[1:4]) # (20, 30, 40)
print(t[:3]) # (10, 20, 30)
print(t[::2]) # (10, 30, 50)
FUNCTIONS OF TUPLE (Built-in Functions)

Function Description Syntax Example Output

Returns the number of elements


len() len(t) len((10, 20, 30)) 3
in the tuple

max() Returns the maximum element max(t) max((5, 12, 8)) 12

min() Returns the minimum element min(t) min((5, 12, 8)) 5

sum() Returns the sum of all elements sum(t) sum((10, 20, 30)) 60

Returns a sorted list (not tuple) sorted((50, 10, [10, 20,


sorted() sorted(t)
of elements 20)) 50]

tuple() Converts a sequence into a tuple tuple(seq) tuple([1, 2, 3]) (1, 2, 3)

Tuple Methods:

Method Description Syntax Example Output

Returns the number of times the


count(x) tuple.count(x) (1, 2, 2, 3).count(2) 2
value x appears in the tuple

Returns the index of the first


(10, 20,
index(x) occurrence of the value x in the tuple.index(x) 1
30).index(20)
tuple
DICTIONARY

1. Introduction to Dictionary

1. A dictionary in Python is an unordered collection of items.


2. Each item is a key-value pair.
3. Dictionaries are mutable (can be changed).
4. Defined using curly braces {} with key:value pairs.

🔹 Example:
student = {'name': 'John', 'age': 16, 'grade': 'A'}

🔹 Output:
{'name': 'John', 'age': 16, 'grade': 'A'}

2. Dictionary - Key:Value Pairs

Key: Must be unique and immutable (string, number, tuple)

Value: Can be any datatype and can be duplicate

Keys are used to access values.

🔹 Example:
car = {
'brand': 'Toyota',
'model': 'Corolla',
'year': 2022
}

Accessing a value:
print(car['model'])

🔹 Output:
Corolla
3. Working with Dictionaries

Operation Code Example Description Output

Returns the value of the


Access a value d['name'] 'John'
key

Adds new key-value to {'city':


Add a new pair d['city'] = 'Delhi'
the dictionary 'Delhi'} added

Changes the value of


Modify a value d['age'] = 17 'age': 17
existing key

Removes
Delete a pair del d['grade'] Deletes key-value pair
'grade' key
Check key Returns True if key
'name' in d True
existence exists
Loop through 'name', 'age',
for k in d: Iterates over keys
keys etc.

Loop through for k, v in d.items(): Iterates through key- name Johnage


items print(k, v) value pairs 16city Delhi

🔹 Example Program:
student = {'name': 'John', 'age': 16, 'grade': 'A'}

# Access
print(student['name'])

# Modify
student['grade'] = 'A+'

# Add
student['city'] = 'Delhi'

# Delete
del student['age']

# Display all items


for key, value in student.items():
print(key, ":", value)

🔹 Output:
John
name : John
grade : A+
city : Delhi
4. Dictionary Functions & Methods

Function/Method Description Example Output


Returns number of
len(d) len({'a': 1, 'b': 2}) 2
key-value pairs
Returns list of dict_keys(['a'
d.keys() {'a': 1}.keys()
keys ])
Returns list of dict_values([1
d.values() {'a': 1}.values()
values ])
Returns list of
dict_items([('
d.items() key-value pairs {'a': 1}.items()
a', 1)])
(tuples)
Returns value for
d.get(key) key, or None if {'a': 1}.get('a') 1
not found
Returns value or
d.get(key, default) default if key {'a': 1}.get('b', 0) 0
not found
Removes specified 1 (dictionary
d.pop(key) key and returns {'a': 1, 'b': 2}.pop('a') becomes {'b':
its value 2})
d.clear() Removes all items {'a': 1}.clear() {}
Updates
d.update(other_dict dictionary with {'a': 1, 'b':
{'a': 1}.update({'b': 2})
) another 2}
dictionary
Returns a shallow
Same as
d.copy() copy of copy = d.copy()
original
dictionary

🔹 Example Program:
d = {'name': 'John', 'age': 25}
print(d['name']) # Accessing value
d['age'] = 30 # Modifying value
d['city'] = 'Delhi' # Adding new key:value
print(d.items()) # Getting all key-value pairs

Output:
John
dict_items([('name', 'John'), ('age', 30), ('city', 'Delhi')])

You might also like