1. map
You can use a for loop to apply something to all elements in a list.
a = [1.2, 2.5, 3.7, 4.6]
for i in range(len(a)):
a[i] = int(a[i])
print(a)
# output: [1,2,3,4]
You can do exactly the same by using map. This is shorter and faster.
a = [1.2, 2.5, 3.7, 4.6]
a = list(map(int, a))
print(a)
# output: [1,2,3,4]
2. *args
def myFunc(*args):
print(args)
myFunc(10, 20, 'a')
# output: (10, 20, 'a')
def myFunc(*args):
print(args)
lst = [10, 20, 'a']
myFunc(*lst)
3. **kwargs
def myFunc(*args, **kwargs):
print(args)
print(kwargs)
myFunc(10, 20,'a', x=100, y=200, z='b')
# output: (10, 20, 'a')
# {'x': 100, 'y': 200, 'z': 'b'}
def myFunc(*args, **kwargs):
print(args)
print(kwargs)
p1 = [10, 20, 'a']
myFunc(*p1,x=100, y=200, z='b')
# output: (10, 20, 'a')
# {'x': 100, 'y': 200, 'z': 'b'}
4. enumerate
lst = [10,20,30]
for idx, val in enumerate(lst):
print(idx, val)