# Planet list#twitter ----------->: @MasudHanif_# Happy Coding..
planet =["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"]for planets in planet:print(f"{planets} from solar system")
fruits =['orange','apple','pear','banana','kiwi','apple','banana']
fruits.count('apple')# count number of apples found in list# output 2
fruits.count('tangerine')# count number of tangerines in list # output 0
fruits.index('banana')# find the first index of banana# output 3
fruits.index('banana',4)# Find next banana starting a position 4# output 6
fruits.reverse()# reverse fruits array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
fruits.append('grape')# append grape at the end of array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
fruits.sort()
fruits
# output ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']len(fruits)# length of fruits array# output 8# loop and print each fruitfor fruit in fruits:print(fruit)
my_list =[1,2,'3',True]# We assume this list won't mutate for each example belowlen(my_list)# 4
my_list.index('3')# 2
my_list.count(2)# 1 --> count how many times 2 appears
my_list[3]# True
my_list[1:]# [2, '3', True]
my_list[:1]# [1]
my_list[-1]# True
my_list[::1]# [1, 2, '3', True]
my_list[::-1]# [True, '3', 2, 1]
my_list[0:3:2]# [1, '3']# : is called slicing and has the format [ start : end : step ]
txt ="this is a wild string"print(txt.replace("i","x"))# print string with all i characters replaced with xprint(txt.replace("i","x",2))# print string with first two i characters found with xprint(txt.upper())# print string in all uppercase lettersprint(txt.lower())# print string in all uppercase lettersprint(ord('A'))# print the ordinal value of a characterprint(chr(95))# print character from its ordinal valueprint('Yes'*5)# print string Yes 5 times# Reference strings by indexprint(txt[0])# print first letter of string from starting indexprint(txt[0:2])# print first two letters from starting indexprint(txt[1:])# print all characters except the first letterprint(txt[0::2])# print every second characterprint(txt[::-1])# print string in reverseprint(txt[-1])# print the last character in a stringprint(txt[-2:])# print the last who characters in a string# check if a wild is found in txtif"wild"in txt:print("wild is found in txt")# check if a blah is not found in txtif"blah"notin txt:print("is not found in txt")# Check if txt starts with thisif txt.startswith("this"):print("Starts with this")# check if txt ends with ingif txt.endswith("ing"):print("Ends with ing")# Split a string into a tuple when the delimiter is first encountered
txt ='random-data'
data_split = txt.partition('-')print(data_split)# output ('random', '-', 'data')len(txt)# Return length of string# loop through each character in stringfor char in txt:print(char)# Display price with commas and 2 digit precision
price =9749000
display_price =f"My price {price:,.2f}"print(display_price)
fruits =['orange','apple','pear','banana','kiwi','apple','banana']
fruits.count('apple')# count number of apples found in list# output 2
fruits.count('tangerine')# count number of tangerines in list# output 0
fruits.index('banana')# find the first index of banana# output 3
fruits.index('banana',4)# Find next banana starting a position 4# output 6
fruits.reverse()# reverse fruits array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
fruits.append('grape')# append grape at the end of array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
fruits.sort()
fruits
# output ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']len(fruits)# length of fruits array# output 8# loop and print each fruitfor fruit in fruits:print(fruit)
empty_set =set()
basket ={'apple','orange','apple','pear','orange','banana'}print(basket)# show that duplicates have been removed# output {'orange', 'banana', 'pear', 'apple'}# check if orange is in basket setprint('orange'in basket)# output true# convert a string to a set of letters - sets contains no duplicates
set_a =set('abcd')
set_b =set('bcde')# the operations below returns new sets# print letters in set_a but not in set_b - differenceprint(set_a - set_b)# output {'a'}# print set letters that is in either set a or b - unionprint(set_a | set_b)# output {'a', 'c', 'e', 'b', 'd'}# print letters that are in both set_a and set_b - intersectionprint(set_a & set_b)# output {'c', 'd', 'b'}# print letters that are in set_a and set_b when the letters are found in a set but no the other set - symmetric_difference()print(set_a ^ set_b)# output {'a', 'e'}# Creating dictionaries
dict1 ={'color':'blue','shape':'square','volume':40}
dict2 ={'color':'red','edges':4,'perimeter':15}# Creating new pairs and updating old ones
dict1['area']=25# {'color': 'blue', 'shape': 'square', 'volume': 40, 'area': 25}
dict2['perimeter']=20# {'color': 'red', 'edges': 4, 'perimeter': 20}# Accessing values through keys - an KeyError will occur if the key does not existsprint(dict1['shape'])# You can also use get, which doesn't cause an exception when the key is not found
dict1.get('false_key')# returns None
dict1.get('false_key',"key not found")# returns the custom message that you wrote# Delete item key and return the value if the key does not exists a KeyError occursprint(dict1.pop('volume'))# Merging two dictionaries
dict1.update(dict2)# if a key exists in both, it takes the value of the second dict
dict1 # {'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}# Getting only the values, keys or both (can be used in loops)
dict1.values()# dict_values(['red', 'square', 25, 4, 20])
dict1.keys()# dict_keys(['color', 'shape', 'area', 'edges', 'perimeter'])
dict1.items()# dict_items([('color', 'red'), ('shape', 'square'), ('area', 25), ('edges', 4), ('perimeter', 20)])# create a shallow copy of dict1
dict3 = dict1.copy()# dict3 = {'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}
list=[1,2,3,4,5,6]print(list)# It will assign value to the value to second index list[2]=10print(list)# Adding multiple element list[1:3]=[89,78]print(list)# It will add value at the end of the list list[-1]=25print(list)
list=[0,1,2,3,4]print("printing original list: ");for i inlist:print(i,end=" ")list.remove(2)print("
printing the list after the removal of first element...")for i inlist:print(i,end=" ")
list1 =[10,20,4,45,99]
mx=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
n =len(list1)for i inrange(2,n):if list1[i]>mx:
secondmax=mx
mx=list1[i]elif list1[i]>secondmax and
mx != list1[i]:
secondmax=list1[i]print("Second highest number is : ",str(secondmax))
Output:-
Second highest number is:45
mylist =[]# creating an empty list# appending values entered by user to listfor i inrange(5):print("Enter value of n[", i,"]")
mylist.append(input())# printing final listprint(mylist)
# Python program to demonstrate# Creation of List# Creating a List
List =[]print("Blank List: ")print(List)# Creating a List of numbers
List =[10,20,14]print("
List of numbers: ")print(List)# Creating a List of strings and accessing# using index
List =["Geeks","For","Geeks"]print("
List Items: ")print(List[0])print(List[2])# Creating a Multi-Dimensional List# (By Nesting a list inside a List)
List =[['Geeks','For'],['Geeks']]print("
Multi-Dimensional List: ")print(List)
# Creating a List
grocery_list =["apple","watermelon","chocolate"]# Appending items to a list
grocery_list.append("milk")# Changing an item on the list
grocery_list[1]="apple juice"# Deleting an item on the list
grocery_list.remove("watermelon")# Sort list in alphabetical order
grocery_list.sort()# Joining lists
utensils =["fork","spoon","steak knife"]list= grocery_list + utensils
# Printing the listsprint(*list, sep=", ")
# A list is a collection of items. # Lists are mutable: you can change their elements and their size.# Similar to List<T> in C#, ArrayList<T> in Java, and array in JavaScript.
foo =[1,2,True,"mixing types is fine"]print(foo[0])# Output - 1
foo[0]=3print(foo[0])# Output - 3
# Planet list#twitter ----------->: @MasudHanif_# Happy Coding..
planet =["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"]for planets in planet:print(f"{planets} from solar system")
fruits =['orange','apple','pear','banana','kiwi','apple','banana']
fruits.count('apple')# count number of apples found in list# output 2
fruits.count('tangerine')# count number of tangerines in list # output 0
fruits.index('banana')# find the first index of banana# output 3
fruits.index('banana',4)# Find next banana starting a position 4# output 6
fruits.reverse()# reverse fruits array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
fruits.append('grape')# append grape at the end of array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
fruits.sort()
fruits
# output ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']len(fruits)# length of fruits array# output 8# loop and print each fruitfor fruit in fruits:print(fruit)
my_list =[1,2,'3',True]# We assume this list won't mutate for each example belowlen(my_list)# 4
my_list.index('3')# 2
my_list.count(2)# 1 --> count how many times 2 appears
my_list[3]# True
my_list[1:]# [2, '3', True]
my_list[:1]# [1]
my_list[-1]# True
my_list[::1]# [1, 2, '3', True]
my_list[::-1]# [True, '3', 2, 1]
my_list[0:3:2]# [1, '3']# : is called slicing and has the format [ start : end : step ]
txt ="this is a wild string"print(txt.replace("i","x"))# print string with all i characters replaced with xprint(txt.replace("i","x",2))# print string with first two i characters found with xprint(txt.upper())# print string in all uppercase lettersprint(txt.lower())# print string in all uppercase lettersprint(ord('A'))# print the ordinal value of a characterprint(chr(95))# print character from its ordinal valueprint('Yes'*5)# print string Yes 5 times# Reference strings by indexprint(txt[0])# print first letter of string from starting indexprint(txt[0:2])# print first two letters from starting indexprint(txt[1:])# print all characters except the first letterprint(txt[0::2])# print every second characterprint(txt[::-1])# print string in reverseprint(txt[-1])# print the last character in a stringprint(txt[-2:])# print the last who characters in a string# check if a wild is found in txtif"wild"in txt:print("wild is found in txt")# check if a blah is not found in txtif"blah"notin txt:print("is not found in txt")# Check if txt starts with thisif txt.startswith("this"):print("Starts with this")# check if txt ends with ingif txt.endswith("ing"):print("Ends with ing")# Split a string into a tuple when the delimiter is first encountered
txt ='random-data'
data_split = txt.partition('-')print(data_split)# output ('random', '-', 'data')len(txt)# Return length of string# loop through each character in stringfor char in txt:print(char)# Display price with commas and 2 digit precision
price =9749000
display_price =f"My price {price:,.2f}"print(display_price)
fruits =['orange','apple','pear','banana','kiwi','apple','banana']
fruits.count('apple')# count number of apples found in list# output 2
fruits.count('tangerine')# count number of tangerines in list# output 0
fruits.index('banana')# find the first index of banana# output 3
fruits.index('banana',4)# Find next banana starting a position 4# output 6
fruits.reverse()# reverse fruits array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
fruits.append('grape')# append grape at the end of array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
fruits.sort()
fruits
# output ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']len(fruits)# length of fruits array# output 8# loop and print each fruitfor fruit in fruits:print(fruit)
empty_set =set()
basket ={'apple','orange','apple','pear','orange','banana'}print(basket)# show that duplicates have been removed# output {'orange', 'banana', 'pear', 'apple'}# check if orange is in basket setprint('orange'in basket)# output true# convert a string to a set of letters - sets contains no duplicates
set_a =set('abcd')
set_b =set('bcde')# the operations below returns new sets# print letters in set_a but not in set_b - differenceprint(set_a - set_b)# output {'a'}# print set letters that is in either set a or b - unionprint(set_a | set_b)# output {'a', 'c', 'e', 'b', 'd'}# print letters that are in both set_a and set_b - intersectionprint(set_a & set_b)# output {'c', 'd', 'b'}# print letters that are in set_a and set_b when the letters are found in a set but no the other set - symmetric_difference()print(set_a ^ set_b)# output {'a', 'e'}# Creating dictionaries
dict1 ={'color':'blue','shape':'square','volume':40}
dict2 ={'color':'red','edges':4,'perimeter':15}# Creating new pairs and updating old ones
dict1['area']=25# {'color': 'blue', 'shape': 'square', 'volume': 40, 'area': 25}
dict2['perimeter']=20# {'color': 'red', 'edges': 4, 'perimeter': 20}# Accessing values through keys - an KeyError will occur if the key does not existsprint(dict1['shape'])# You can also use get, which doesn't cause an exception when the key is not found
dict1.get('false_key')# returns None
dict1.get('false_key',"key not found")# returns the custom message that you wrote# Delete item key and return the value if the key does not exists a KeyError occursprint(dict1.pop('volume'))# Merging two dictionaries
dict1.update(dict2)# if a key exists in both, it takes the value of the second dict
dict1 # {'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}# Getting only the values, keys or both (can be used in loops)
dict1.values()# dict_values(['red', 'square', 25, 4, 20])
dict1.keys()# dict_keys(['color', 'shape', 'area', 'edges', 'perimeter'])
dict1.items()# dict_items([('color', 'red'), ('shape', 'square'), ('area', 25), ('edges', 4), ('perimeter', 20)])# create a shallow copy of dict1
dict3 = dict1.copy()# dict3 = {'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}
list=[1,2,3,4,5,6]print(list)# It will assign value to the value to second index list[2]=10print(list)# Adding multiple element list[1:3]=[89,78]print(list)# It will add value at the end of the list list[-1]=25print(list)
list=[0,1,2,3,4]print("printing original list: ");for i inlist:print(i,end=" ")list.remove(2)print("
printing the list after the removal of first element...")for i inlist:print(i,end=" ")
list1 =[10,20,4,45,99]
mx=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
n =len(list1)for i inrange(2,n):if list1[i]>mx:
secondmax=mx
mx=list1[i]elif list1[i]>secondmax and
mx != list1[i]:
secondmax=list1[i]print("Second highest number is : ",str(secondmax))
Output:-
Second highest number is:45
mylist =[]# creating an empty list# appending values entered by user to listfor i inrange(5):print("Enter value of n[", i,"]")
mylist.append(input())# printing final listprint(mylist)
# Python program to demonstrate# Creation of List# Creating a List
List =[]print("Blank List: ")print(List)# Creating a List of numbers
List =[10,20,14]print("
List of numbers: ")print(List)# Creating a List of strings and accessing# using index
List =["Geeks","For","Geeks"]print("
List Items: ")print(List[0])print(List[2])# Creating a Multi-Dimensional List# (By Nesting a list inside a List)
List =[['Geeks','For'],['Geeks']]print("
Multi-Dimensional List: ")print(List)
# Creating a List
grocery_list =["apple","watermelon","chocolate"]# Appending items to a list
grocery_list.append("milk")# Changing an item on the list
grocery_list[1]="apple juice"# Deleting an item on the list
grocery_list.remove("watermelon")# Sort list in alphabetical order
grocery_list.sort()# Joining lists
utensils =["fork","spoon","steak knife"]list= grocery_list + utensils
# Printing the listsprint(*list, sep=", ")
# A list is a collection of items. # Lists are mutable: you can change their elements and their size.# Similar to List<T> in C#, ArrayList<T> in Java, and array in JavaScript.
foo =[1,2,True,"mixing types is fine"]print(foo[0])# Output - 1
foo[0]=3print(foo[0])# Output - 3