Skip to content
Home » 14 Hidden Python Features for Beginners (Part- 1)

14 Hidden Python Features for Beginners (Part- 1)

😊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 🙂

Leave a Reply

Generated by Feedzy