0% found this document useful (0 votes)
30 views7 pages

Python Revision 1 and 2 Full 1

The document contains various Python code snippets demonstrating string manipulation, list operations, dictionary methods, and other programming concepts. Each snippet illustrates specific functions and methods, such as capitalize, count, join, and pop, among others. The examples are structured in a sequential manner, covering a wide range of Python functionalities.

Uploaded by

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

Python Revision 1 and 2 Full 1

The document contains various Python code snippets demonstrating string manipulation, list operations, dictionary methods, and other programming concepts. Each snippet illustrates specific functions and methods, such as capitalize, count, join, and pop, among others. The examples are structured in a sequential manner, covering a wide range of Python functionalities.

Uploaded by

svvsuganyacbse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

1 s = "hello WORLD" 2 s = "multiple WORDS IN a String"

res = s.capitalize() res = s.capitalize()


print(res) print(res)
3 s = "123hello WORLD" 4 string = "GEEKSFORGEEKS"
res = s.capitalize() print("lowercase string: ",
print(res) string.casefold())

5 string = "geeks for geeks" 6 string = "geeks for geeks"


new_string = new_string = string.center(24, '#')
string.center(24) print("After padding String is:",
print("After padding String new_string)
is: ", new_string)

7 s = "hello world" 8 s = "Python is fun and Python is powerful."


res = s.count("o") print(s.count("Python"))
print(res)
9 s = "apple banana apple grape apple" 10 s = "apple banana apple grape apple"
substring = "apple" substring = "apple"
res = s.count(substring, 1, 20) res = s.count(substring, 8, 20)
print(res) print(res)
11. string = "geeksforgeeks" 12 text = "geeks for geeks."
print(string.endswith("geeks")) result = text.endswith('geeks.', 10)
print(result)
13 text = "geeks for geeks." 14 s = "Welcome to GeekforGeeks!"
result = text.endswith('geeks.', 10,16) index = s.find("GeekforGeeks")
print(result) print(index)
15 s = "abc abc abc" 16 s = "Python is fun"
index = s.find("abc", 4) index = s.find("python")
print(index) print(index)
17 s = "Python programming" 18 s = "Python programming is fun"
position = s.index("prog") position = s.index("is", 10, 25)
print(position) print(position)
19 a = ['Hello', 'world', 'from', 'Python'] 20 s = ("Learn", "to", "code")
res = ' '.join(a) res = "-".join(s)
print(res) print(res)

21 s = {'Python', 'is', 'fun'} 22 d = {'Geek': 1, 'for': 2, 'Geeks': 3}


res = '-'.join(s) res = '_'.join(d)
print(res) print(res)
23 s = ' ##*#Hello Python!#**## ' 24 s = '\nHello Python!\n'
res = s.lstrip('#* ') # Removing newline characters
print(res) # from the end of string
res = s.lstrip()
print(res)
24 str = "I love Geeks for 25 string = "light attracts bug"
geeks" # 'attracts' separator is found
print(str.partition("for")) print(string.partition('attracts'))

string = "gold is heavy"


# 'is' as partition
print(string.partition('is'))
25 s = "Hello World! Hello Python!" 26. s = "apple apple apple"
# Replace "Hello" with "Hi" # Replace "apple" with "orange" only
s1 = s.replace("Hello", "Hi") once
print(s1) s1 = s.replace("apple", "orange", 1)
print(s1)
27 s = "Hello, World! hello, world!" 28 a = [2, 5, 6, 7]
# Replace only lowercase 'hello' # Use append() to add the element 8
s1 = s.replace("hello", "hi") # to the end of the list
print(s1) a.append(8)
# Replace only uppercase 'Hello' print(a)
s2 = s.replace("Hello", "Hi")
print(s2)
29 a = [1, 2, 3] 30 a = [1, 2, 3]
a.append([4, 5]) b = [4, 5]
print(a) # Using extend() to add elements of b
to a
a.extend(b)
print(a)
31 Animals= ["cat", "dog", "tiger"] 32 # list of items
# searching positiion of dog list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
print(Animals.index("dog")) # Will print index of '4' in sublist
# having index from 4 to 8.
print(list1.index(4, 4, 8))
33 # list of items 34 # Python3 program for demonstration
list1 = [6, 8, 5, 6, 1, 2] # of index() method error
# Will print index of '6' in sublist list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
# having index from 1 to end of the list. # Return ValueError
print(list1.index(6, 1)) print(list1.index(10))
35 # Declaring a list with random integers. 36 # Declaring a list with mixed values.
list1 = ['a', '$', 'e', 'E'] list1 = ['a', '$', 'e', 3, 16]
# Store maximum value in a variable # Store maximum value in a variable
# using Python list max() function. # using Python list max() function.
maxValue = max(list1) maxValue = max(list1)
# Printing value stored in maxValue. # Printing value stored in maxValue.
print(maxValue) print(maxValue)
37 languages = ["Python", "C 38 languages = ["Python", "C
Programming", "Java", Programming", "Java",
"JavaScript",'PHP','Kotlin'] "JavaScript",'PHP','Kotlin']
s= max(languages) small = min(languages)
print("The largesrst string is:", s) print("The smallest string is:", small)
39 square = {5: 25, 8: 64, 2: 4, 3: 9, -1: 1, -2: 40 # Python3 program to Find elements
4} of a
# list by indices present in
print("The smallest key:", min(square))
another list
print(“The largest key:”,max(square))
def findElements(lst1, lst2):
return [lst1[i] for i in lst2]
# Driver code
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))

41 # List with three elements 42 a = [1, 2, 3, 4, 1, 2, 6]


li = [1, 2, 3]
a.reverse()
# Unpacking list elements into variables print(a)
a, b, c = li
print(a)
print(b)
print(c)
43 a = [1, [2, 3], 1, [2, 3], 1] 44 a = [1, 2, 3]
c = a.count([2, 3]) # Copy the list
b = a.copy()
print(c) # Add an element to the copied list
b.append(4)
print('a:', a)
print('b:', b)
45 a = [1, 2, 3] 46. a = [[1, 2], [3, 4]]
# Copy the list b = a.copy()
b = a # Modify the value at index 0,0 in
# Add an element to the copied the copied list
list b[0][0] = 100
b.append(4) print("a:", a)
print('a:', a) print("b:", b)
print('b:', b)
47 a = [1, 'two', 3.0, [4, 5], {'key': 'value'}] 48 my_list = [{'name': 'Alice', 'age':
b = a.copy() 30}, {'name': 'Bob', 'age': 25}]
new_dict = {'name': 'Charlie',
# Add an element (6) in the copied list at 'age': 40}
index 3 my_list.append(new_dict)
b[3].append(6) print(my_list)
print("a:", a)
print("b:", b)
49 a = ["apple", "banana", "kiwi", "cherry"] 50 a = [(1, 3), (2, 2), (3, 1)]
# The key=len tells the sort() method def fun(val):
return val[1]
# to use length of each string during a.sort(key=fun)
sorting print(a)
a.sort(key=len)
print(a)
51 a = ["Banana", "apple", "Grape", "pear"] 52 original = {1: 'geeks', 2: 'for'}
a.sort(key=str.lower) # copying using copy() function
print(a) new = original.copy()
# removing all elements from the
list
# Only new list becomes empty as
copy()
# does shallow copy.
new.clear()
print('new: ', new)
print('original: ', original)

53 # given dictionary 54 eq = {'a', 'b', 'c', 'd', 'e'}


dict1 = {10: 'a', 20: [1, 2, # creating dict with default values
3], 30: 'c'} as None
print("Given Dictionary:", res_dict = dict.fromkeys(seq)
dict1) print("The newly created dict with
# new dictionary and None values : " + str(res_dict))
# copying using copy() method # creating dict with default values
dict2 = dict1.copy() as 1
print("New copy:", dict2) res_dict2 = dict.fromkeys(seq, 1)
# Updating dict2 elements and print("The newly created dict with
# checking the change in dict1 1 as value : " + str(res_dict2))
dict2[10] = 10
dict2[20][2] = '45'
# list item updated
print("Updated copy:", dict2)

55 seq = ('a', 'b', 'c') 56 d = {'coding': 'good', 'thinking':


print(dict.fromkeys(seq, 'better'}
None)) print(d.get('coding'))

57 # Python program to show working 58 test_dict = {'Gfg' : {'is' :


# of items() method in Dictionary 'best'}}
# printing original dictionary
# Dictionary with three items print("The original dictionary is :
Dictionary1 = { 'A': 'Geeks', 'B': 4, 'C': " + str(test_dict))
'Geeks' } # using nested get()
print("Dictionary items:") # Safe access nested dictionary key
# Printing all the items of the Dictionary res = test_dict.get('Gfg',
{}).get('is')
print(Dictionary1.items())
# printing result
print("The nested safe
59 d = {1: '001', 2: '010', 3: '011'} 60 # Dictionary with three keys
print(d.get(4, "Not found")) Dictionary1 = {'A': 'Geeks', 'B':
'For', 'C': 'Geeks'}
# Printing keys of dictionary
print(Dictionary1.keys())
61 # Python program to show 62 # initializing dictionary
working test_dict = {"geeks": 7, "for": 1,
# of items() method in "geeks": 2}
Dictionary # accessing 2nd element using naive
# Dictionary with three items method
Dictionary1 = { 'A': 'Geeks', # using loop
'B': 4, 'C': 'Geeks' } j = 0
print("Original Dictionary for i in test_dict:
items:") if (j == 1):
items = Dictionary1.items() print('2nd key using loop : ' + i)
# Printing all the items of j = j + 1
the Dictionary
print(items)
# Delete an item from
dictionary
del[Dictionary1['C']]
print('Updated Dictionary:')
print(items)
63 # initializing dictionary 64 # Dictionary with two keys
test_dict = {"geeks": 7, Dictionary1 = {'A': 'Geeks', 'B':
"for": 1, "geeks": 2} 'For'}
# accessing 2nd element using # Printing keys of dictionary
keys() print("Keys before Dictionary
print('2nd key using keys() : Updation:")
', list(test_dict.keys())[1]) keys = Dictionary1.keys()
print(keys)
# adding an element to the
dictionary
Dictionary1.update({'C': 'Geeks'})
print('\nAfter dictionary is
updated:')
print(keys)
65 # inializing dictionary 66 # initializing dictionary
student race_rank = {"Rahul":8,"Aditya":1,
student = {"rahul":7, "Madhur": 5}
"Aditya":1, "Shubham":4} # removing a value-key
# priting original dictionary race_rank.pop("Rahul")
print(student) #printing new dictionary
# using dictionary pop print(race_rank)
suspended =
student.pop("rahul")
# checking key of the element
print("suspended student roll
no. = "+ str(suspended))
# printing list after
performing pop()
print("remaining student" +
str(student))

67 # Python 3 code to demonstrate 68 est_dict = {"Nikhil": 7, "Akshat":


# working of pop() 1, "Akash": 2}
# initializing dictionary
test_dict = {"Nikhil": 7, # Printing initial dict
"Akshat": 1, "Akash": 2} print("Before using popitem(),
# Printing initial dict test_dict: ", test_dict)
print("The dictionary before
deletion : " + str(test_dict)) # using popitem() to return+
# using pop to return and # remove the last keym value pair
remove key-value pair. res = test_dict.popitem()
pop_ele = test_dict.pop('Akash')
# Printing the value
associated to popped key # Printing the pair returned
print("Value associated to print('The key, value pair returned
is : ', res)
popped key is : " +
str(pop_ele)) # Printing dict after deletion
# Printing dictionary after print("After using popitem(),
deletion test_dict: ", test_dict)
print("Dictionary after
deletion is : " +
str(test_dict))

69 d = {1: '001', 2: '010', 3: 70 d = {'a': 97, 'b': 98, 'c': 99,


'011'} 'd': 100}
print(d.popitem()) # space key added using
setdefault() method
d.setdefault(' ', 32)
print(d)

71 d = {'a': 97, 'b': 98} 72 Dictionary1 = { 'A': 'Geeks', 'B':


print("setdefault() 'For'}
returned:", d.setdefault('b', print("Dictionary before using
99)) setdefault():", Dictionary1)
print("After using
setdefault():", d) # using setdefault() when key is
non-existing
ret_value =
Dictionary1.setdefault('C',
"Geeks")
print("Return value of
setdefault():", ret_value)
print("Dictionary after using
setdefault():", Dictionary1)
73 # update() method in 74 # Dictionary with three items
Dictionary d1 = {'A': 'Geeks', 'B': 'For', }
d2 = {'B': 'Geeks', 'C': 'Python'}
# Dictionary with three items
d1 = {'A': 'Geeks', 'B':
'For', } # update the value of key 'B'
d2 = {'B': 'Geeks', 'C': d1.update(d2)
'Python'}
print(d1)

# update the value of key 'B'


d1.update(d2)

# using keyword arguments


d1.update(A='Hello')

print(d1)
75 # Define dictionary 76 # numerical values
d = {'m': 700, 'n': 100, 't': dictionary = {"raj": 2, "striver":
500} 3, "vikram": 4}
print(dictionary.values())
# Key to check
key = 'k'

# Check if key exists and # string values


update dictionary = {"geeks": "5", "for":
if key not in d: "3", "Geeks": "5"}
print("Key doesn't exist. print(dictionary.values())
Adding a new key-value pair.")
d[key] = 600 # Direct
assignment
else:
print("Key exists.")

# Print updated dictionary


print(d)
77 # stores name and 78 # when parameter is not passed
corresponding salaries tuple1 = tuple()
salary = {"raj" : 50000, print("empty tuple:", tuple1)
"striver" : 60000, "vikram" :
# when an iterable(e.g., list) is
5000}
passed
list1= [ 1, 2, 3, 4 ]
# stores the salaries only tuple2 = tuple(list1)
list1 = salary.values() print("list to tuple:", tuple2)
print(sum(list1)) # prints the
sum of all salaries # when an iterable(e.g., string) is
passed
string = "geeksforgeeks";
tuple4 = tuple(string)
print("str to tuple:", tuple4)
79. my_tuple = (1, 2, 3, 4, 5) 80 my_dict = {'apple': 1, 'banana': 2,
print(my_tuple[1:4]) 'cherry': 3}
my_tuple = tuple(my_dict.items())
print(my_tuple)
81 my_tuple = tuple((1, 2, 3))
print(max(my_tuple))

You might also like