Friday, February 2, 2024

Python Tricks Part-1

Python - Tricks - Part-1


  1. Printing Horizontally 

Default it will print one after another

list1 = [1, 3, 6, 7]
for number in list1:
print(number,end=" ")




2. Print using separator

print(1,2,3,4, sep="|") 




3. Merging Dictionaries using pipe |

agegen1 = { "prasad":38, "dilip" : 33}
agegen2 = { "karthik":12, "Maanas" : 6}
agegen = agegen1 | agegen2
print(agegen) 


4. Merging Dictionaries using pipe **

agegen1 = { "prasad":38, "dilip" : 33}
agegen2 = { "karthik":12, "Maanas" : 6}
agegen = {**agegen1 , **agegen2}
print(agegen) 


5. Calendar with Python

import calendar
year_2024_isleap_year = calendar.isleap(2024)
year_2023_isleap_year = calendar.isleap(2023)
if year_2024_isleap_year == True:
print("Year 2024 is leap Year")
else:
print("Year 2024 is not a leap Year")
if year_2023_isleap_year == True:
print("Year 2023 is leap Year")
else:
print("Year 2023 is not leap Year") 


 

6. Get current time and Date

from datetime import datetime
time_now = datetime.now()
print("Timestamp Now: ",time_now)

time_now = datetime.now().strftime('%H:%M:%S')
print("Time Now: ",time_now)

from datetime import date
date_now = date.today()

print("Today's Date: ",date_now) 



 

 7. Sort a List in descending order

list1 = [11,1,3,5,8,4,2]
list1.sort(reverse = True)
print(list1) 


8. Swapping Variables

x, y = 10, 40
print("x is ", x)
print("y is ", y)
x, y = y, x
print("x is ", x)
print("y is ", y) 

9. Counting Item Occurrences

from collections import Counter
list1 = ['Karthik','Maanas','Karthik','Prasad','Dilip']
count_karthik = Counter(list1).get('Karthik')
print(f'Karthik Appears {count_karthik} times') 


 

 10. Flatten the list

#method 1
list1 = [[1,2,3],[3,5,6]]
newlist = []
for list2 in list1:
for i in list2:
newlist.append(i)
print('method 1', newlist)

#method 2
import itertools
newlist1 = list(itertools.chain.from_iterable(list1))
print('method 2', newlist1)

#method 3
newlist2 = [i for j in list1 for i in j]
print('method 3', newlist2) 


 

No comments:

Post a Comment

Python Tricks Part-1

Python - Tricks - Part-1 Printing Horizontally  Default it will print one after another list1 = [ 1 , 3 , 6 , 7 ] for number in list1: ...