The key-value pairs of a dictionary can be directly passed as named parameters to any function in the same way we passed a list before.
d = {'age': 25, 'name': 'Jane'}
def showdata(name, age):
print(f'{name} is {age} years old')
showdata(**d)
We normally use the range() function or an inerrable object to create a for loop. We can also create a for loop with multiple interactable objects using the zip() function.
keys = ['Name', 'age']
values = ['John', '22']
for i, j in zip(keys, values):
print(f'{i}: {j}')
Python allows you to easily swap the keys and values of a dictionary using the same syntax we use for dictionary comprehension. Here’s an example.
d = {1: 'One', 2: 'Two', 3: 'Three'}
di = { v:k for k, v in d.items()}
print(di)
Usually, we flatten a list of lists using a couple of nested for loops. Although this method works fine, it makes our code larger. So, here’s a shorter method to flatten a list using the itertools module.
import itertools
a = [[1, 2], [3, 4]]
b = list(itertools.chain.from_iterable(a))
print(b)
In Python, you can pass the elements of a list as individual parameters without specifying it manually by index using the * operator. This is also known as unpacking.
l = [5, 6]
def sum(x, y):
print(x + y)
sum(*l)
With the join method Python, we can easily convert the items of a list to string.
l = ['Join', 'this', 'string']
print(str.join(' ', l))
How do you usually shuffle the items in a list? Most of the Python beginners will be using a loop to iterate over the list and shuffle the items. But python has an inbuilt method to shuffle list items. To use this method, we should first import random module.
from random import shuffle
l = [1, 2, 3]
shuffle(l)
print(l)
You will get different outputs each time you run the code.
There are several methods to do this.
x = "Hi from Geekinsta"
substr = "Geekinsta"
# Method 1
if substr in x:
print("Exists")
# Method 2
if x.find(substr) >=0:
print("Exists")
# Method 3
if x.__contains__(substr):
print("Exists")
Following is a list of employees in company with their ID and salary.
emp=[
['EMPCT01', 10000],
['EMPCT02', 20000],
['EMPCT03', 80000],
['EMPCT04', 30000]
]
How will you sort the emp in ascending order based on the salary. Ie, starting with the one with the lowest salary to the highest-paid one.
emp=[
['EMPCT01', 10000],
['EMPCT02', 20000],
['EMPCT04', 30000],
['EMPCT03', 80000]
]
Solution:
emp=[
['EMPCT01', 10000],
['EMPCT02', 20000],
['EMPCT03', 80000],
['EMPCT04', 30000]
]
emp.sort(key=lambda els: int(els[1]))
print(emp)
Hey, you can multiply strings in Python.
print("Geekinsta " * 3)
Output:
Geekinsta Geekinsta Geekinsta