šHere are some lesser-known but useful features of the Python for everyday use.Ā š
1. Merge Dictionaries
>>> d1 = {“a”:1, “b”: 2}
>>> d2 = {“c”:3, “d”:4}
>>> dict(d1, **d2)
{āaā: 1, ‘bā: 2, ‘cā: 3, ‘dā: 4}
>>> {**d1, **d2}
{āaā: 1, ‘bā: 2, ‘cā: 3, ‘dā: 4}
2. JoinĀ Strings
>>> arr = [“hello”, āthere”, “python”, “learning”]
>>> “-“.join(arr)
‘hello-there-python-learning’
>>> ā “.join(arr)
‘hello there python learning’
3. Max occurrence of an item from aĀ list
>>> arr = [1, 2, 2, 4, 2, 2, 3, 1, 5, 4, 4]
>>> max(set(arr), key = arr.count)
2
4. ValuesĀ Swapping
>>> a, b = 2, 5
>>> a, b = b, a
>>> print(a, b)
5 2
5. Range intoĀ list
>>> arr = list(range(1, 11))
>>> arr
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
6. List Comprehension
>>> square = [i**2 for i in range(1, 11)]
>>> square
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
7. Dict Comprehension
>>> from string import ascii_lowercase
>>> {i:j for i, j in enumerate(ascii_lowercase) if i < 6}
{0: ‘aā, 1: ‘bā, 2: ‘cā, 3: ‘dā, 4: ‘eā, 5: ‘fā}
>>> {j:i for i, j in enumerate(ascii_lowercase) if i < 6}
{āaā: 0, ‘bā: 1, ‘cā: 2, ‘dā: 3, ‘eā: 4, ‘fā: 5}>>> {i: i for i in range(6)}
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
8. AddingĀ lists
>>> l1 = [1, 2, 3, 4]
>>> l2 = [5, 6, 7, 8]
>>> l1 + l2
[1, 2, 3, 4, 5, 6, 7, 8]
>>> l1.append(l2)
>>> l1
[1, 2, 3, 4, [5, 6, 7, 8]]
>>> l1 = [1, 2, 3, 4]
>>> [i+j for i, j in zip(l1, l2)]
[6, 8, 10, 12]
9. Extraction of NestedĀ list
>>> List1 = [[1], [2], [3], [4], [5]]
>>> sum(List1, [])
[1, 2, 3, 4, 5]
10. Print Unique Items fromĀ List
>>> List1 = [1, 1, 1, 2, 3, 4, 5, 1, 2, 3, 1, 5]
>>> list(set(list1))
[1, 2, 3, 4, 5]
11. printās end arguments
12. printās sepĀ argument
>>> print(āhelloā, āthereā, ā!!!ā, sep=ā ā ā)
hello ā there ā !!!
>>> print(āhelloā, āthereā, ā!!!ā, sep=ā**ā)
hello**there**!!!
13. List appendĀ Method
>>> list1 = [1, 2]
>>> list2 = [3, 4]
>>> list1.append(list2)
>>> list1
[1, 2, [3, 4]]
14. List extendĀ Method
>>> list1 = [1, 2]
>>> list2 = [3, 4]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4]
Follow Us on Instagram for moreĀ š