Tuesday, 8 July 2025

Python - 2

Text Type: 

str 

Numeric Types: 

int, float, complex 

Sequence Types: 

list, tuple, range 

Mapping Type: 

dict 

Set Types: 

set, frozenset 

Boolean Type: 

bool 

 

 

 

Example 

Data Type 

x = "Hello World" 

str 

x = 20 

int 

x = 20.5 

float 

x = 1j 

complex 

x = ["apple", "banana", "cherry"] 

print(x[0]) 

list 

x = ("apple", "banana", "cherry") 

print(x[0]) 

tuple 

x = range(6) 

range 

x = {"name" : "John", "age" : 36} 

dict 

x = {"apple", "banana", "cherry"} 

set 

x = frozenset({"apple", "banana", "cherry"}) 

frozenset 

x = True 

bool 

x = b"Hello" 

bytes 

x = bytearray(5) 

bytearray 

x = memoryview(bytes(5)) 

memoryview 

 

 

print(type(x))   → type of variable 

 

 

 

Type Casting 

 

Str() 

float() 

int() 

 

 

LIST 

 

thislist = ["apple", "banana", "cherry"] 

for x in thislist: 

  print(x) 

 

Check if Item Exists 

thislist = ["apple", "banana", "cherry"] 

if "apple" in thislist: 

  print("Yes, 'apple' is in the fruits list") 

 

 

List Length 

thislist = ["apple", "banana", "cherry"] 

print(len(thislist)) 

 

Add Items 

thislist = ["apple", "banana", "cherry"] 

thislist.append("orange") 

print(thislist) 

 

Insert an item as the second position: 

thislist = ["apple", "banana", "cherry"] 

thislist.insert(1, "orange") 

print(thislist) 

 

 

The remove() method removes the specified item: 

thislist = ["apple", "banana", "cherry"] 

thislist.remove("banana") 

print(thislist) 

 

 

 

The clear() method empties the list: 

thislist = ["apple", "banana", "cherry"] 

thislist.clear() 

print(thislist) 

 

 

List Methods 

Python has a set of built-in methods that you can use on lists. 

Method 

Description 

Adds an element at the end of the list 

Removes all the elements from the list 

Returns a copy of the list 

Returns the number of elements with the specified value 

Add the elements of a list (or any iterable), to the end of the current list 

Returns the index of the first element with the specified value 

Adds an element at the specified position 

Removes the element at the specified position 

Removes the item with the specified value 

Reverses the order of the list 

Sorts the list 

 

Second highest salary 

 

list1 = [5000, 10000, 200,3,3000] 

print(list1) 

list1.sort(reverse=True) 

print(list1[1]) 

 

________________________ 

Sort the list by the length of the values: 

# A function that returns the length of the value: 

def myFunc(e): 

  return len(e) 

 

cars = ['Ford', 'Mitsubishi', 'BMW', 'VW'] 

 

cars.sort(key=myFunc) 

for car in cars: 

print(car) 

 

___________________________ 

 

 

Sort a list of dictionaries based on the "year" value of the dictionaries: 

# A function that returns the 'year' value: 

def myFunc(e): 

  return e['year'] 

 

cars = [ 

  {'car': 'Ford', 'year': 2005}, 

  {'car': 'Mitsubishi', 'year': 2000}, 

  {'car': 'BMW', 'year': 2019}, 

  {'car': 'VW', 'year': 2011} 

] 

 

cars.sort(key=myFunc) 

______________ 

 

List has Dict value  

listkeys = [{"Name": "Shet", "Company": "MMMM"},{"Name": "Rajiv", "Company": "Mphasis"}] 

 

for listkey in listkeys: 

print(listkey["Name"]) 

_________ 

 

 

 

 

Tuple 

A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. 

 

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. 

But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple. 

x = ("apple", "banana", "cherry") 

y = list(x) 

y[1] = "kiwi" 

x = tuple(y) 

 

print(x) 

 

 

 

thistuple = ("apple", "banana", "cherry") 

for x in thistuple: 

  print(x) 

 

 

thistuple = ("apple", "banana", "cherry") 

if "apple" in thistuple: 

  print("Yes, 'apple' is in the fruits tuple") 

 

 

thistuple = ("apple", "banana", "cherry") 

print(len(thistuple)) 

 

 

 

Set 

A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets. 

Example 

Create a Set: 

thisset = {"apple", "banana", "cherry"} 

print(thisset) 

 

 

Dictionary 

 

thisdict = { 

  "brand": "Ford", 

  "model": "Mustang", 

  "year": 1964 

} 

print(thisdict) 

 

 

Print all key names in the dictionary, one by one: 

for x in thisdict: 

  print(x) 

 

 

Print all values in the dictionary, one by one: 

for x in thisdict: 

  print(thisdict[x]) 

 

Date 

 

Display the name of the month: 

 

import datetime 

x = datetime.datetime(2018, 6, 1) 

print(x.strftime("%B")) 

 

try: 

  f = open("demofile.txt") 

  f.write("Lorum Ipsum") 

except: 

  print("Something went wrong when writing to the file") 

finally: 

  f.close() 

 

String format() 

Add a placeholder where you want to display the price: 

price = 49 

txt = "The price is {} dollars" 

print(txt.format(price)) 

quantity = 3 

itemno = 567 

price = 49 

myorder = "I want {} pieces of item number {} for {:.2f} dollars." 

print(myorder.format(quantity, itemno, price)) 

name = 'esh' 

print(name.upper()) 

print(len(name)) 

print(name[0]) 

for char in name: 

print(char) 

print(name[2:len(name)]) 

 

#reverse print - slice - the slice statement [::-1] means start at the end of the string and end at position 0, move with the step -1, negative one, which means one step backwards 

revName = name [::-1] 

print(revName) 

 

 

 

#lst 4 char 

print(name[-4:]) 

 

 

 

String S 

H 

e 

l 

l 

o 

Index 

S[0] 

S[1] 

S[2] 

S[3] 

S[4] 

Index 

S[-5] 

S[-4] 

S[-3] 

S[-2] 

S[-1] 

 

 

 

#substring  

print(name[2:len(name)]) 

 

 

s = 'abracadabra' 

print(s.find('b')) 

# 1 

print(s.rfind('b')) 

# 8 

 

 

print('a bar is a bar, essentially'.replace('bar', 'pub')) 

 

 

print('Abracadabra'.count('a')) 

# 4 

print(('aaaaaaaaaa').count('aa')) 

# 5 

 

 

 

Feature 

List 

Set 

Tuple 

Dictionary 

Definition 

Ordered, mutable collection 

Unordered, mutable, no duplicates 

Ordered (immutable), fixed 

Key-value pairs 

Syntax 

[1, 2, 3] 

{1, 2, 3} 

(1, 2, 3) 

{'a': 1, 'b': 2} 

Duplicates 

✅ Allowed 

❌ Not allowed 

✅ Allowed 

❌ Keys, ✅ Values 

Mutable 

✅ Yes 

✅ Yes 

❌ No 

✅ Yes 

Indexed 

✅ Yes (0-based) 

❌ No indexing 

✅ Yes (0-based) 

✅ By keys 

Use Case 

Ordered data collection 

Unique items, fast lookup 

Fixed, ordered data 

Fast key-based lookups 

Access Value 

my_list[0] 

Use loop: for x in my_set: 

my_tuple[0] 

my_dict['a'] 

Add Item 

my_list.append(4) 

my_set.add(4) 

❌ Not allowed 

my_dict['c'] = 3 

Remove Item 

my_list.remove(2) 

my_set.remove(2) 

❌ Not allowed 

del my_dict['a'] 

Print Values 

print(my_list)[1, 2, 3] 

for x in my_set: print(x) 

print(my_tuple)(1, 2, 3) 

for k, v in my_dict.items(): print(k, v) 

Example 

[1, 2, 3] 

{1, 2, 3} 

(1, 2, 3) 

{'a': 1, 'b': 2} 

 

AWS Lambda example 

 

🔹 Example 1: Upload a File to an S3 Bucket 

import boto3 
 
# Initialize S3 client 
s3 = boto3.client('s3') 
 
# Upload a file 
s3.upload_file('local_file.txt', 'my-s3-bucket-name', 'uploaded_file.txt') 
 
print("✅ File uploaded to S3 successfully.") 
 

Use Case: Automate data backups or upload logs to S3. 

 

🔹 Example 2: Start an EC2 Instance 

import boto3 
 
# Initialize EC2 client 
ec2 = boto3.client('ec2') 
 
# Start EC2 instance 
response = ec2.start_instances(InstanceIds=['i-0123456789abcdef0']) 
 
print("✅ Starting instance:", response['StartingInstances'][0]['InstanceId']) 
 

Use Case: Automate instance management for dev/test environments. 

 

 

How to get all keys and value from dict 

 

Dict1 = {'key1': 1, 'key2': 2, 'key3': 3} 

 

for k, v in dict1.items(): 

    print(k, v) 

 

File operations with Python 

 

Read file 

 

f = open("demofile.txt", "r") 

 

print(f.read()) 

 

 

 

Loop through the file line by line: 

f = open("demofile.txt", "r") 

for x in f: 

  print(x) 

 

Write 

‘A’ = append 

‘W’ =write 

f = open("demofile2.txt", "a") 

f.write("Now the file has more content!") 

f.close() 

 

#open and read the file after the appending: 

f = open("demofile2.txt", "r") 

print(f.read()) 

 

Call Rest API and render page 

 

import requests  

data ='{ "query": { "bool": “True” }' 

 

response = requests.post(url, data=data) 

Lambda with profile 

Picture 

 

Lambda with STS 

Picture 

 

Enumeration (or enum) in Python is a way to define a set of named, constant values. It’s commonly used when you have a fixed set of related values 

 

🔹 Basic Enum Usage 

Here’s a simple example to illustrate the basics: 

from enum import Enum 
 
class Color(Enum): 
   RED = 1 
   GREEN = 2 
   BLUE = 3 
 

Now, you can use the Color enum like this: 

python 

 

print(Color.RED)        # Color.RED 
print(Color.RED.name)   # 'RED' 
print(Color.RED.value)  # 1 
 

🔹 Accessing Enums 

python 

 

# Access by name 
print(Color['GREEN'])  # Color.GREEN 
 
# Access by value 
print(Color(2))        # Color.GREEN 
 

🔹 Iterating Over Enums 

python 

 

for color in Color: 
   print(color.name, color.value) 

 

 

🔹 zip – For Pairing Iterables 

zip takes two or more iterables (lists, tuples, etc.) and combines them element-wise into tuples. 

✅ Example: 

python 

 

names = ['Alice', 'Bob', 'Charlie'] 
balances = [1200, 1500, 1000] 
 
combined = list(zip(names, balances)) 
print(combined) 
# [('Alice', 1200), ('Bob', 1500), ('Charlie', 1000)] 

 


🔁 Comparison Table

Featureboto3.client()boto3.Session() + .client()
Credential SourceUses default credentialsCan use a specific profile/role
Profile Switching❌ Not easy✅ Easy with profile_name
Multi-account Access❌ Complex✅ Controlled via custom session
Explicit Session Mgmt❌ Hidden✅ Full control
ReusabilityGood for simple scriptsBetter for large apps or multi-account use
Thread SafetyNot idealSessions are safer for threading

No comments:

Post a Comment