Search

Python Programming Filter

How to Stand Out in a Python Coding Interview - Functions, Data Structures & Libraries

Any coding interview is a test which primarily focuses on your technical skills and algorithm knowledge. However, if you want to stand out among the hundreds of interviewees, you should know how to use the common functionalities of Python in a convenient manner.The type of interview you might face can be a remote coding challenge, a whiteboard challenge or a full day on-site interview. So if you can prove your coding skills at that moment, the job letter will reach you in no time. You may go through some of the top Python interview questions and answers provided by experts which are divided into three levels- beginner, intermediate and advanced. A thorough practice of these questions and answers on Python will definitely help you achieve your dream job as a Python Developer, Full Stack engineer, and other top profiles.A Python coding interview is basically a technical interview. They are not just about solving problems, they are more about how technically sound you are and how you can write clean productive Python code. This will show your depth of knowledge about Python and how you can use Python’s built-in functions and libraries to implement your code. Go through our Python Tutorials to learn more about  concepts related to Python. Let us look into some of the built-in functions provided by Python and how to select the correct one, learn about the effective use of data structures, how standard libraries in Python can be utilized and so on.How to Select the Correct Built-in Function?Python’s library of built-in functions is small as compared to the standard library. The built-in functions are always available and are not needed to be imported. It is suggested to learn each function before sitting for the interview. Till then, let us learn a few built-in functions and how to use them and also what alternatives can be used.Perform iteration with enumerate() instead of range() Consider a situation during a coding interview: You have a list of elements and you have to iterate over the list with the access to both the indices and values. To differentiate between iteration with enumerate()  and iteration with range(), let us take a look at the classic coding interview question FizzBuzz. It can be solved by iterating over both indices and values. You will be given a list of integers and your task will be as follows:Replace all integers that are evenly distributed by 3 with “fizz”.Replace all integers divisible by 5 with “buzz”.Replace all integers divisible by 3 and 5 with “fizzbuzz”.Developers make use of range() in these situations which can access the elements by index:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i in range(len(list_num)):       if list_num[i] % 3 == 0 and list_num[i] % 5 == 0:           list_num[i] = 'fizzbuzz'       elif list_num[i] % 3 == 0:           list_num[i] = 'fizz'       elif list_num[i] % 5 == 0:           list_num[i] = 'buzz'   >>> list_num ['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']Though range() can be used in a lot of iterative methods, it is better to use enumerate() in this case since it can access the element’s index and value at the same time:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i,num in enumerate(list_num):       if list_num[i] % 3 == 0 and list_num[i] % 5 == 0:           list_num[i] = 'fizzbuzz'       elif list_num[i] % 3 == 0:           list_num[i] = 'fizz'       elif list_num[i] % 5 == 0:           list_num[i] = 'buzz' >>> list_num ['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']The enumerate() function returns a counter and the element value for each element. The counter is set to 0 by default which is also the element’s index.  However, if you are not willing to start your counter from 0, you can set an offset using the start parameter:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i, num in enumerate(list_num, start=11):       print(i, num) 11 30 12 29 13 10 14 65 14 95 16 99You can access all of the same elements using the start parameter. However, the count will start from the specified integer value.Using List Comprehensions in place of map() and filter()Python supports list comprehensions which are easier to read and are analogous in functionality as map() and filter(). This is one of the reasons why Guido van Rossum, the creator of Python felt that dropping map() and filter() was quite uncontroversial.An example to show  map() along with this equivalent list comprehension:>>> list_num = [1, 2, 3, 4, 5, 6] >>> def square_num(z): ...    return z*z ... >>> list(map(square_num, list_num)) [1, 4, 9, 16, 25, 36] >>> [square_num(z) for z in numbers] [1, 4, 9, 16, 25, 36]Though map() and list comprehension returns the same values but the list comprehension part is easier to read and understand.An example to show  filter() and its equivalent list comprehension:>>> def odd_num_check(z):       return bool(z % 2)   >>> list(filter(odd_num_check, num_list)) [1, 3, 5] >>> [z for z in numbers if odd_num_check(z)] [1, 3, 5]It is the same with filter()as it was with map(). The return values are the same but the list comprehension is easier to follow.List comprehensions are easier to read and beginners are able to catch it more intuitively.Though other programming language developers might argue to the fact but if you make use of list comprehensions during your coding interview, it is more likely to communicate your knowledge about the common functionalities to the recruiter.Debugging With breakpoint() instead of print() Debugging is an essential part of writing software and it shows your knowledge of Python tools which will be useful in developing quickly in your job in the long run. However, using print() to debug a small problem might be good initially but your code will become clumsy. On the other hand, if you use a debugger like breakpoint(), it will always act faster than print().If you’re using Python 3.7, you can simply call breakpoint() at the point in your code where you want to debug without the need of importing anything:# Complicated Code With Bugs ... ... ... breakpoint()Whenever you call breakpoint(), you will be put into The Python Debugger - pdb. However, if you’re using Python 3.6 or older, you can perform an explicit importing which will be exactly like calling breakpoint():import pdb; pdb.set_trace()In this example, you’re being put into the pdb by the pdb.set_trace().  Since it’s a bit difficult to remember, it is recommended to use breakpoint() whenever a debugger is needed. There are also other debuggers that you can try. Getting used to debuggers before your interview would be a great advantage but you can always come back to pdb since it’s a part of the Python Standard Library and is always available. Formatting Strings with the help of f-StringsIt can be confusing to know what type of string formatting should we use since Python consists of a number of different string formatting techniques. However, it is a good approach and is suggested to use Python’s f-strings during a coding interview for Python 3.6 or greater.Literal String Interpolation or f-strings is a powerful string formatting technique that is more readable, more concise, faster and less prone to error than other formatting techniques. It supports the string formatting mini-language which makes string interpolation simpler. You also have the option of adding new variables and Python expressions and they can be evaluated before run-time:>>> def name_and_age(name, age):       return f"My name is {name} and I'm {age / 10:.5f} years old."   >>> name_and_age("Alex", 21) My name is Alex and I'm 2.10000 years old.The f-string allows you to add the name Alex into the string and his corresponding age with the type of formatting you want in one single operation.Note that it is suggested to use Template Strings if the output consists of user-generated values.Sorting Complex Lists with sorted()There are a lot of interview questions that are mostly based on sorting and it is one of the most important concepts you should be clear about before you sit for a coding interview. However, it is always a better option to use sorted() unless you are asked to make your own sorting algorithm by the interviewer.Example code to illustrate simple uses of sorting like sorting numbers or strings:>>> sorted([6,5,3,7,2,4,1]) [1, 2, 3, 4, 5, 6, 7] >>> sorted(['IronMan', 'Batman', 'Thor', 'CaptainAmerica', 'DoctorStrange'], reverse=False) ['Batman', 'CaptainAmerica', 'DoctorStrange', 'IronMan', 'Thor']sorted() performs sorting in ascending order by default and also when the reverse argument is set to False. If you sorting complex data types, you might want to add a function which allows custom sorting rules:>>> animal_list = [ ...    {'type': 'bear', 'name': 'Stephan', 'age': 9}, ...    {'type': 'elephant', 'name': 'Devory', 'age': 5}, ...    {'type': 'jaguar', 'name': 'Moana', 'age': 7}, ... ] >>> sorted(animal_list, key=lambda animal: animal['age']) [     {'type': 'elephant', 'name': 'Devory', 'age': 5},     {'type': 'jaguar', 'name': 'Moana', 'age': 7},     {'type': 'bear, 'name': 'Stephan, 'age': 9}, ]You can easily sort a list of dictionaries using the lambda keyword. In the example above, the lambda returns each element’s age and the dictionary is sorted in ascending order by age.Effective Use of Data StructuresData Structures are one of the most important concepts you should know before getting into an interview and if you choose the perfect data structure during an interviewing context, it will certainly impact your performance. Python’s standard data structure implementations are incredibly powerful and give a lot of default functionalities which will surely be helpful in coding interviews.Storing Values with SetsMake use of sets instead of lists whenever you want to remove duplicate elements from an existing dataset.Consider a function random_word that always returns a random word from a set of words:>>> import random >>> words = "all the words in the world".split() >>> def random_word():       return random.choice(words)In the example above, you need to call random_word repeatedly to get 1000 random selections and then return a data structure that will contain every unique word.Let us look at three approaches to execute this – two suboptimal approaches and one good approach.Bad Approach An example to store values in a list and then convert into a set:>>> def unique_words():       words = []       for _ in range(1000):           words.append(random_word())       return set(words) >>> unique_words() {'planet', 'earth', 'to', 'words'}In this example, creating a list and then converting it into a set is an unnecessary approach. Interviewers notice this type of design and questions about it generally.Worse ApproachYou can store values into a list to avoid the conversion from list to a set. You can then check for the uniqueness by comparing new values with all current elements in the list:>>> def unique_words():       words = []       for _ in range(1000):     word = unique_words()     if word not in words:     words.append(word)       return words >>> unique_words() {'planet', 'earth', 'to', 'words'}This approach is much worse than the previous one since you have to compare every word to every other word already present in the list. In simple terms, the time complexity is much greater in this case than the earlier example.Good ApproachIn this example, you can skip the lists and use sets altogether from the beginning:>>> def unique_words():       words = set()       for _ in range(1000):           words.add(random_word())       return words >>> unique_words() {'planet', 'earth', 'to', 'words'}This approach differs from the second approach as the storing of elements in this approach allows near-constant-time-checks whether a value is present in the set or not whereas linear time-lookups were required when lists were used. The time complexity for this approach is O(N) which is much better than the second approach whose time complexity grew at the rate of O(N²).Saving Memory with GeneratorsThough lists comprehensions are convenient tools, it may lead to excessive use of memory.Consider a situation where you need to find the sum of the first 1000 squares starting with 1 using list comprehensions:>>> sum([z * z for z in range(1, 1001)])333833500Your solution returns the correct answer by making a list of every perfect square and then sums the values. However, the interviewer asks you to increase the number of perfect squares. Initially, your program might work well but it will gradually slow down and the process will be changed completely.  However, you can resolve this memory issue just by replacing the brackets with parentheses:>>> sum((z * z for z in range(1, 1001)))333833500When you make the change from brackets to parentheses, the list comprehension changes to generator expressions. It returns a generator object. The object calculates the next value only when asked. Generators are mainly used on massive sequences of data and in situations when you want to retrieve data from a sequence but don’t want to access all of it at the same time.Defining Default Values in Dictionaries with .get() and .setdefault()Adding, modifying or retrieving an item from a dictionary is one of the most primitive tasks of programming and it is easy to perform with Python functionalities. However, developers often check explicitly for values even its not necessary.Consider a situation where a dictionary named shepherd exists and you want to get that cowboy’s name by explicitly checking for the key with a conditional:>>> shepherd = {'age': 20, 'sheep': 'yorkie', 'size_of_hat': 'large'} >>> if 'name' in shepherd:       name = shepherd['name']     else:       name = 'The Man with No Name'   >>> nameIn this example, the key name is searched in the dictionary and the corresponding value is returned otherwise a default value is returned.You can use .get() in a single line instead of checking keys explicitly:>>> name = shepherd.get('name', 'The Man with No Name')The get() performs the same operation as the first approach does, but they are now handled automatically. However, .get() function does not help in situations where you need to update the dictionary with a default value while still accessing the same key. In such a case, you again need to use explicit checking:>>> if 'name' not in shepherd:       shepherd['name'] = 'The Man with No Name'   >>> name = shepherd['name']However, Python still offers a more elegant way of performing this approach using .setdefault():>>> name = shepherd.setdefault('name', 'The Man with No Name')The .setdefault() function performs the same operation as the previous approach did. If name exists in shepherd, it returns a value otherwise it sets shepherd[‘name’]  to The Man with No Name and returns a new value.Taking Advantage of the Python Standard LibraryPython’s functionalities are powerful on its own and all the things can be accessed just by using the import statement. If you know how to make good use of the standard library, it will boost your coding interview skills.How to handle missing dictionaries?You can use .get() and .setdefault() when you want to set a default for a single key. However, there will be situations where you will need to set a default value for all possible unset keys, especially during the context of a coding interview.Consider you have a  group of students and your task is to keep track of their grades on assignments. The input value is a tuple with student_name and grade. You want to look upon all the grades for a single student without iterating over the whole list. An example to store grade data using a dictionary:>>> grades_of_students = {} >>> grades = [       ('alex', 89),       ('bob', 95),       ('charles', 81),       ('alex', 94),       ] >>> for name, grade in grades:       if name not in grades_of_student:           grades_of_student[name] = []       grades_of_student[name].append(grade) >>> student_grades{'alex': [89, 94], 'bob': [95], 'charles': [81]}In the example above, you iterate over the list and check if the names are already present in the dictionary or not. If it isn’t, then you add them to the dictionary with an empty list and then append their actual grades to the student’s list of grades.However, the previous approach is good but there is a cleaner approach for such cases using the defaultdict:>>> from collections import defaultdict >>> student_grades = defaultdict(list) >>> for name, grade in grades:       student_grades[name].append(grade)In this approach, a defaultdict is created that uses the list() with no arguments. The list()returns an empty list. defaultdict calls the list() if the name does not exist and then appends the grade.Using the defaultdict, you can handle all the common default values at once and need not worry about default values at the key level. Moreover, it generates a much cleaner application code.How to Count Hashable Objects?Pretend you have a long string of words with no punctuation or capital letters and you are asked to count the number of the appearance of each word. In this case, you can use collections.Counter that uses 0 as the default value for any missing element and makes it easier and cleaner to count the occurrence of different objects:>>> from collections import Counter >>> words = "if I am there but if \ ... he was not there then I was not".split() >>> counts = Counter(words) >>> countsCounter({'if': 2, 'there': 2, 'was': 1, 'not': 2, 'but': 1, ‘I’: 2, ‘am’: 1, }When the list is passed to Counter, it stores each word and also the number of occurrences of that word in the list.If you want to know the two most common words in a list of strings like above, you can use .most_common() which simply returns the n most frequently inputs by count:>>> counts.most_common(2)[('if': 2), ('there': 2), ('not': 2), (‘I’: 2)] How to Access Common String Groups?If you want to check whether ‘A’ > ‘a’ or not, you have to do it using the ASCII chart. The answer will be false since the ASCII value for A is 65 and a is 97, which is clearly greater. However, it would be a difficult task to remember the ASCII code when it comes to lowercase and uppercase ASCII characters and also this method is a bit clumsy. You can use the much easier and convenient constants which are a part of the string module. An example to check whether all the characters in a string are uppercase or not:>>> import string >>> def check_if_upper(word):       for letter in word:           if letter not in string.ascii_uppercase:               return False       return True   >>> check_if_upper('Thanks Alex') False >>> check_if_upper('ROFL') TrueThe function check_if_upper iterates over the letters in words, and checks whether the letters are part of string.ascii_uppercase. It is set to the literal ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.There are a number of string constants that are frequently used for referencing string values that are easy to read and use. Some of which are as follows:string.ascii_lettersstring.ascii_upercasestring.ascii_lowercasestring.ascii_digitsstring.ascii_hexdigitsstring.ascii_octdigitsstring.ascii_punctuationstring.ascii_printablestring.ascii_whitespaceConclusionClearing interview with confidence and panache is a skill. You might be a good programmer but it’s only a small part of the picture. You might fail to clear a few interviews, but if you follow a good process, it will certainly help you in the long run. Being enthusiastic is an important factor that will have a huge impact on your interview results. In addition to that is practice. Practice always helps. Brush up on all the common interview concepts and then head off to practicing different interview questions. Interviewers also help during interviews if you can communicate properly and interact. Ask questions and always talk through a brute-force and optimized solution.Let us now sum up what we have learned in this article so far:To use enumerate() to iterate over both indices and values.To debug problematic code with breakpoint().To format strings effectively with f-strings.To sort lists with custom arguments.To use generators instead of list comprehensions to save memory.To define default values when looking up dictionary keys.To count hashable objects with collections.Counter class.Hope you have learned about most of the powerful Python’s built-in functions, data structures, and standard library packages that will help you in writing better, faster and cleaner code. Though there are a lot of other things to learn about the language, join our Python certification course to gain more skills and knowledge.
Rated 4.5/5 based on 14 customer reviews

How to Stand Out in a Python Coding Interview - Functions, Data Structures & Libraries

6328
How to Stand Out in a Python Coding Interview - Functions, Data Structures & Libraries

Any coding interview is a test which primarily focuses on your technical skills and algorithm knowledge. However, if you want to stand out among the hundreds of interviewees, you should know how to use the common functionalities of Python in a convenient manner.

The type of interview you might face can be a remote coding challenge, a whiteboard challenge or a full day on-site interview. So if you can prove your coding skills at that moment, the job letter will reach you in no time. You may go through some of the top Python interview questions and answers provided by experts which are divided into three levels- beginner, intermediate and advanced. A thorough practice of these questions and answers on Python will definitely help you achieve your dream job as a Python Developer, Full Stack engineer, and other top profiles.

A Python coding interview is basically a technical interview. They are not just about solving problems, they are more about how technically sound you are and how you can write clean productive Python code. This will show your depth of knowledge about Python and how you can use Python’s built-in functions and libraries to implement your code. Go through our Python Tutorials to learn more about  concepts related to Python. Let us look into some of the built-in functions provided by Python and how to select the correct one, learn about the effective use of data structures, how standard libraries in Python can be utilized and so on.

How to Select the Correct Built-in Function?

Python’s library of built-in functions is small as compared to the standard library. The built-in functions are always available and are not needed to be imported. It is suggested to learn each function before sitting for the interview. Till then, let us learn a few built-in functions and how to use them and also what alternatives can be used.

Perform iteration with enumerate() instead of range() 

Consider a situation during a coding interview: You have a list of elements and you have to iterate over the list with the access to both the indices and values. 

To differentiate between iteration with enumerate()  and iteration with range(), let us take a look at the classic coding interview question FizzBuzz. It can be solved by iterating over both indices and values. You will be given a list of integers and your task will be as follows:

  1. Replace all integers that are evenly distributed by 3 with “fizz”.
  2. Replace all integers divisible by 5 with “buzz”.
  3. Replace all integers divisible by 3 and 5 with “fizzbuzz”.

Developers make use of range() in these situations which can access the elements by index:

>>> list_num = [30, 29, 10, 65, 95, 99]
>>> for i in range(len(list_num)):
      if list_num[i] % 3 == 0 and list_num[i] % 5 == 0:
          list_num[i] = 'fizzbuzz'
      elif list_num[i] % 3 == 0:
          list_num[i] = 'fizz'
      elif list_num[i] % 5 == 0:
          list_num[i] = 'buzz'
 
>>> list_num
['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']

Though range() can be used in a lot of iterative methods, it is better to use enumerate() in this case since it can access the element’s index and value at the same time:

>>> list_num = [30, 29, 10, 65, 95, 99]
>>> for i,num in enumerate(list_num):
      if list_num[i] % 3 == 0 and list_num[i] % 5 == 0:
          list_num[i] = 'fizzbuzz'
      elif list_num[i] % 3 == 0:
          list_num[i] = 'fizz'
      elif list_num[i] % 5 == 0:
          list_num[i] = 'buzz'

>>> list_num
['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']

The enumerate() function returns a counter and the element value for each element. The counter is set to 0 by default which is also the element’s index.  

However, if you are not willing to start your counter from 0, you can set an offset using the start parameter:

>>> list_num = [30, 29, 10, 65, 95, 99]
>>> for i, num in enumerate(list_num, start=11):
      print(i, num) 
11 30
12 29
13 10
14 65
14 95
16 99

You can access all of the same elements using the start parameter. However, the count will start from the specified integer value.

Using List Comprehensions in place of map() and filter()

Python supports list comprehensions which are easier to read and are analogous in functionality as map() and filter(). This is one of the reasons why Guido van Rossum, the creator of Python felt that dropping map() and filter() was quite uncontroversial.

An example to show  map() along with this equivalent list comprehension:

>>> list_num = [1, 2, 3, 4, 5, 6]
>>> def square_num(z):
...    return z*z
...
>>> list(map(square_num, list_num))
[1, 4, 9, 16, 25, 36]

>>> [square_num(z) for z in numbers]
[1, 4, 9, 16, 25, 36]

Though map() and list comprehension returns the same values but the list comprehension part is easier to read and understand.

An example to show  filter() and its equivalent list comprehension:

>>> def odd_num_check(z):
      return bool(z % 2)
 
>>> list(filter(odd_num_check, num_list))
[1, 3, 5]

>>> [z for z in numbers if odd_num_check(z)]
[1, 3, 5]

It is the same with filter()as it was with map(). The return values are the same but the list comprehension is easier to follow.

List comprehensions are easier to read and beginners are able to catch it more intuitively.

Though other programming language developers might argue to the fact but if you make use of list comprehensions during your coding interview, it is more likely to communicate your knowledge about the common functionalities to the recruiter.

Debugging With breakpoint() instead of print() 

Debugging is an essential part of writing software and it shows your knowledge of Python tools which will be useful in developing quickly in your job in the long run. However, using print() to debug a small problem might be good initially but your code will become clumsy. On the other hand, if you use a debugger like breakpoint(), it will always act faster than print().

If you’re using Python 3.7, you can simply call breakpoint() at the point in your code where you want to debug without the need of importing anything:

# Complicated Code With Bugs
...
...
...
breakpoint()

Whenever you call breakpoint(), you will be put into The Python Debugger - pdb. However, if you’re using Python 3.6 or older, you can perform an explicit importing which will be exactly like calling breakpoint():

import pdb; pdb.set_trace()

In this example, you’re being put into the pdb by the pdb.set_trace().  Since it’s a bit difficult to remember, it is recommended to use breakpoint() whenever a debugger is needed. There are also other debuggers that you can try. Getting used to debuggers before your interview would be a great advantage but you can always come back to pdb since it’s a part of the Python Standard Library and is always available. 

Formatting Strings with the help of f-Strings

It can be confusing to know what type of string formatting should we use since Python consists of a number of different string formatting techniques. However, it is a good approach and is suggested to use Python’s f-strings during a coding interview for Python 3.6 or greater.

Literal String Interpolation or f-strings is a powerful string formatting technique that is more readable, more concise, faster and less prone to error than other formatting techniques. It supports the string formatting mini-language which makes string interpolation simpler. You also have the option of adding new variables and Python expressions and they can be evaluated before run-time:

>>> def name_and_age(name, age):
      return f"My name is {name} and I'm {age / 10:.5f} years old."
 
>>> name_and_age("Alex", 21)
My name is Alex and I'm 2.10000 years old.

The f-string allows you to add the name Alex into the string and his corresponding age with the type of formatting you want in one single operation.

Note that it is suggested to use Template Strings if the output consists of user-generated values.

Sorting Complex Lists with sorted()

There are a lot of interview questions that are mostly based on sorting and it is one of the most important concepts you should be clear about before you sit for a coding interview. However, it is always a better option to use sorted() unless you are asked to make your own sorting algorithm by the interviewer.

Example code to illustrate simple uses of sorting like sorting numbers or strings:

>>> sorted([6,5,3,7,2,4,1])
[1, 2, 3, 4, 5, 6, 7]

>>> sorted(['IronMan', 'Batman', 'Thor', 'CaptainAmerica', 'DoctorStrange'], reverse=False)
['Batman', 'CaptainAmerica', 'DoctorStrange', 'IronMan', 'Thor']

sorted() performs sorting in ascending order by default and also when the reverse argument is set to False. 

If you sorting complex data types, you might want to add a function which allows custom sorting rules:

>>> animal_list = [
...    {'type': 'bear', 'name': 'Stephan', 'age': 9},
...    {'type': 'elephant', 'name': 'Devory', 'age': 5},
...    {'type': 'jaguar', 'name': 'Moana', 'age': 7},
... ]
>>> sorted(animal_list, key=lambda animal: animal['age'])
[
    {'type': 'elephant', 'name': 'Devory', 'age': 5},
    {'type': 'jaguar', 'name': 'Moana', 'age': 7},
    {'type': 'bear, 'name': 'Stephan, 'age': 9},
]

You can easily sort a list of dictionaries using the lambda keyword. In the example above, the lambda returns each element’s age and the dictionary is sorted in ascending order by age.

Effective Use of Data Structures

Data Structures are one of the most important concepts you should know before getting into an interview and if you choose the perfect data structure during an interviewing context, it will certainly impact your performance. 

Python’s standard data structure implementations are incredibly powerful and give a lot of default functionalities which will surely be helpful in coding interviews.

Storing Values with Sets

Make use of sets instead of lists whenever you want to remove duplicate elements from an existing dataset.

Consider a function random_word that always returns a random word from a set of words:

>>> import random
>>> words = "all the words in the world".split()
>>> def random_word():
      return random.choice(words)

In the example above, you need to call random_word repeatedly to get 1000 random selections and then return a data structure that will contain every unique word.

Let us look at three approaches to execute this – two suboptimal approaches and one good approach.

Bad Approach 

An example to store values in a list and then convert into a set:

>>> def unique_words():
      words = []
      for _ in range(1000):
          words.append(random_word())
      return set(words)
>>> unique_words()
{'planet', 'earth', 'to', 'words'}

In this example, creating a list and then converting it into a set is an unnecessary approach. Interviewers notice this type of design and questions about it generally.

Worse Approach

You can store values into a list to avoid the conversion from list to a set. You can then check for the uniqueness by comparing new values with all current elements in the list:

>>> def unique_words():
      words = []
      for _ in range(1000):
    word = unique_words()
    if word not in words:
    words.append(word)
      return words
>>> unique_words()
{'planet', 'earth', 'to', 'words'}

This approach is much worse than the previous one since you have to compare every word to every other word already present in the list. In simple terms, the time complexity is much greater in this case than the earlier example.

Good Approach

In this example, you can skip the lists and use sets altogether from the beginning:

>>> def unique_words():
      words = set()
      for _ in range(1000):
          words.add(random_word())
      return words
>>> unique_words()
{'planet', 'earth', 'to', 'words'}

This approach differs from the second approach as the storing of elements in this approach allows near-constant-time-checks whether a value is present in the set or not whereas linear time-lookups were required when lists were used. The time complexity for this approach is O(N) which is much better than the second approach whose time complexity grew at the rate of O(N²).

Saving Memory with Generators

Though lists comprehensions are convenient tools, it may lead to excessive use of memory.

Consider a situation where you need to find the sum of the first 1000 squares starting with 1 using list comprehensions:

>>> sum([z * z for z in range(1, 1001)])
333833500

Your solution returns the correct answer by making a list of every perfect square and then sums the values. However, the interviewer asks you to increase the number of perfect squares. 

Initially, your program might work well but it will gradually slow down and the process will be changed completely.  

However, you can resolve this memory issue just by replacing the brackets with parentheses:

>>> sum((z * z for z in range(1, 1001)))
333833500

When you make the change from brackets to parentheses, the list comprehension changes to generator expressions. It returns a generator object. The object calculates the next value only when asked. 

Generators are mainly used on massive sequences of data and in situations when you want to retrieve data from a sequence but don’t want to access all of it at the same time.

Defining Default Values in Dictionaries with .get() and .setdefault()

Adding, modifying or retrieving an item from a dictionary is one of the most primitive tasks of programming and it is easy to perform with Python functionalities. However, developers often check explicitly for values even its not necessary.

Consider a situation where a dictionary named shepherd exists and you want to get that cowboy’s name by explicitly checking for the key with a conditional:

>>> shepherd = {'age': 20, 'sheep': 'yorkie', 'size_of_hat': 'large'}
>>> if 'name' in shepherd:
      name = shepherd['name']
    else:
      name = 'The Man with No Name'
 
>>> name

In this example, the key name is searched in the dictionary and the corresponding value is returned otherwise a default value is returned.

You can use .get() in a single line instead of checking keys explicitly:

>>> name = shepherd.get('name', 'The Man with No Name')

The get() performs the same operation as the first approach does, but they are now handled automatically. 

However, .get() function does not help in situations where you need to update the dictionary with a default value while still accessing the same key. In such a case, you again need to use explicit checking:

>>> if 'name' not in shepherd:
      shepherd['name'] = 'The Man with No Name'
 
>>> name = shepherd['name']

However, Python still offers a more elegant way of performing this approach using .setdefault():

>>> name = shepherd.setdefault('name', 'The Man with No Name')

The .setdefault() function performs the same operation as the previous approach did. If name exists in shepherd, it returns a value otherwise it sets shepherd[‘name’]  to The Man with No Name and returns a new value.

Taking Advantage of the Python Standard Library

Python’s functionalities are powerful on its own and all the things can be accessed just by using the import statement. If you know how to make good use of the standard library, it will boost your coding interview skills.

How to handle missing dictionaries?

You can use .get() and .setdefault() when you want to set a default for a single key. However, there will be situations where you will need to set a default value for all possible unset keys, especially during the context of a coding interview.

Consider you have a  group of students and your task is to keep track of their grades on assignments. The input value is a tuple with student_name and grade. You want to look upon all the grades for a single student without iterating over the whole list. 

An example to store grade data using a dictionary:

>>> grades_of_students = {}
>>> grades = [
      ('alex', 89),
      ('bob', 95),
      ('charles', 81),
      ('alex', 94),
      ]
>>> for name, grade in grades:
      if name not in grades_of_student:
          grades_of_student[name] = []
      grades_of_student[name].append(grade)

>>> student_grades
{'alex': [89, 94], 'bob': [95], 'charles': [81]}

In the example above, you iterate over the list and check if the names are already present in the dictionary or not. If it isn’t, then you add them to the dictionary with an empty list and then append their actual grades to the student’s list of grades.

However, the previous approach is good but there is a cleaner approach for such cases using the defaultdict:

>>> from collections import defaultdict
>>> student_grades = defaultdict(list)
>>> for name, grade in grades:
      student_grades[name].append(grade)

In this approach, a defaultdict is created that uses the list() with no arguments. The list()returns an empty list. defaultdict calls the list() if the name does not exist and then appends the grade.

Using the defaultdict, you can handle all the common default values at once and need not worry about default values at the key level. Moreover, it generates a much cleaner application code.

How to Count Hashable Objects?

Pretend you have a long string of words with no punctuation or capital letters and you are asked to count the number of the appearance of each word. In this case, you can use collections.Counter that uses 0 as the default value for any missing element and makes it easier and cleaner to count the occurrence of different objects:

>>> from collections import Counter
>>> words = "if I am there but if \
... he was not there then I was not".split()
>>> counts = Counter(words)
>>> counts
Counter({'if': 2, 'there': 2, 'was': 1, 'not': 2, 'but': 1, ‘I’: 2, ‘am’: 1, }

When the list is passed to Counter, it stores each word and also the number of occurrences of that word in the list.

If you want to know the two most common words in a list of strings like above, you can use .most_common() which simply returns the n most frequently inputs by count:

>>> counts.most_common(2)
[('if': 2), ('there': 2), ('not': 2), (‘I’: 2)]
How to Access Common String Groups?

If you want to check whether ‘A’ > ‘a’ or not, you have to do it using the ASCII chart. The answer will be false since the ASCII value for A is 65 and a is 97, which is clearly greater. 

However, it would be a difficult task to remember the ASCII code when it comes to lowercase and uppercase ASCII characters and also this method is a bit clumsy. You can use the much easier and convenient constants which are a part of the string module

An example to check whether all the characters in a string are uppercase or not:

>>> import string
>>> def check_if_upper(word):
      for letter in word:
          if letter not in string.ascii_uppercase:
              return False
      return True
 
>>> check_if_upper('Thanks Alex')
False
>>> check_if_upper('ROFL')
True

The function check_if_upper iterates over the letters in words, and checks whether the letters are part of string.ascii_uppercase. It is set to the literal ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.

There are a number of string constants that are frequently used for referencing string values that are easy to read and use. Some of which are as follows:

  • string.ascii_letters
  • string.ascii_upercase
  • string.ascii_lowercase
  • string.ascii_digits
  • string.ascii_hexdigits
  • string.ascii_octdigits
  • string.ascii_punctuation
  • string.ascii_printable
  • string.ascii_whitespace

Conclusion

Clearing interview with confidence and panache is a skill. You might be a good programmer but it’s only a small part of the picture. You might fail to clear a few interviews, but if you follow a good process, it will certainly help you in the long run. Being enthusiastic is an important factor that will have a huge impact on your interview results. In addition to that is practice. Practice always helps. Brush up on all the common interview concepts and then head off to practicing different interview questions. Interviewers also help during interviews if you can communicate properly and interact. Ask questions and always talk through a brute-force and optimized solution.

Let us now sum up what we have learned in this article so far:

  • To use enumerate() to iterate over both indices and values.
  • To debug problematic code with breakpoint().
  • To format strings effectively with f-strings.
  • To sort lists with custom arguments.
  • To use generators instead of list comprehensions to save memory.
  • To define default values when looking up dictionary keys.
  • To count hashable objects with collections.Counter class.

Hope you have learned about most of the powerful Python’s built-in functions, data structures, and standard library packages that will help you in writing better, faster and cleaner code. Though there are a lot of other things to learn about the language, join our Python certification course to gain more skills and knowledge.

Priyankur

Priyankur Sarkar

Data Science Enthusiast

Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

Scala Vs Python Vs R Vs Java - Which language is better for Spark & Why?

One of the most important decisions for the Big data learners or beginners is choosing the best programming language for big data manipulation and analysis. Just understanding business problems and choosing the right model is not enough but implementing them perfectly is equally important and choosing the right language (or languages) for solving the problem goes a long way. If you search top and highly effective programming languages for Big Data on Google, you will find the following top 4 programming languages: JavaScalaPythonRJavaJava is one of the oldest languages of all 4 programming languages listed here. Traditional Frameworks of Big data like Apache Hadoop and all the tools within its ecosystem are Java-based and hence using java opens up the possibility of utilizing large ecosystem of tools in the big data world.  ScalaA beautiful crossover between object-oriented and functional programming language is Scala. Scala is a highly Scalable Language. Scala was invented by the German Computer Scientist, Martin Odersky and the first version was launched in the year 2003.PythonPython was originally conceptualized by Guido van Rossum in the late 1980s. Initially, it was designed as a response to the ABC programming language and later gained its popularity as a functional language in a big data world. Python has been declared as one of the fastest-growing programming languages in 2018 as per the recently held Stack Overflow Developer Survey. Many data analysis, manipulation, machine learning, deep learning libraries are written in Python and hence it has gained its popularity in the big data ecosystem. It’s a very user-friendly language and it is its biggest advantage.  Fun factPython is not named after the snake. It’s named after the British TV show Monty Python.RR is the language of statistics. R is a language and environment for statistical computing and graphics. R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is currently developed by the R Development Core Team. R is named partly after the first names of the first two R authors and partly as a play on the name of S*. The project was conceived in 1992, with an initial version released in 1995 and a stable beta version in 2000.*SS is a statistical programming language developed primarily by John Chambers and R is an implementation of the S programming language combined with lexical scoping semantics, inspired by Scheme.Every framework is implemented in the underlying programming language for its implementation. Ex Zend uses PHP, Panda Framework uses python similarly Hadoop framework uses Java and Spark uses Scala.However, Spark officially supports Java, Scala, Python and R, all 4 languages. If one browses through Apache Spark’s official website documentation, he/she would find many other languages utilized by the open-source community for Spark implementation.    When any developer wants to start learning Spark, the first question he stumbles upon is, out of these pools of languages, which one to use and which one to master? Solution Architects would have a tough time choosing the right language for spark framework and Organizations will always be wondering, which skill sets are relevant for my problem if one doesn’t have the right knowledge about these languages in the context of Spark.    This article will try to answer all these queries.so let’s start-JavaOldest of all and popular, widely adopted programming language of all. There is a number offeatures/advantages due to which Java is favorite for Big data developers and tool creators:Java is platform-agnostic language and hence it can run on almost any system. Java is portable due to something called Java Virtual Machine – JVM. JVM is a foundation of Hadoop ecosystem tools like Map Reduce, Storm, Spark, etc. These tools are written in Java and run on JVM.Java provides various communities support like GitHub and stack overflow etc.Java is scalable, backward compatible, stable and production-ready language. Also, supports a large variety of tried and tested libraries.It is statically typed language (We would see details of this functionality in later sections, in comparison with others)Java is mostly the choice for most of the big data projects but for the Spark framework, one has to ponder upon, whether Java would be the best fit.One major drawback of Java is its verbosity. One has to write long code (number of lines of code) to achieve simple functionality in Java.Java does not support Read-Evaluate-Print-Loop (REPL) which is a major deal-breaker when choosing a programming language for big data processing.ScalaScala is comparatively new to the programming scene but has become popular very quickly. Above are a few quotes from bigger names in the industry for Scala. From the Spark context, many experts prefer Scala over other programming languages as Spark is written in Scala. Scala is the native language of Spark. It means any new API always first be available in Scala.Scala is a hybrid functional programming language because It has both the features of object-oriented programming and functional programming. As an OO Programming Language, it considers every value as an object and all OOPS concepts apply. As a functional programming language, it defines and supports functions. All operations are done as functions. No variable stands by itself. Scala is a machine-compiled language.Scala and Java are popular programming languages that run over JVM. JVM makes these languages framework friendly. One can say, Scala is an advanced level of Java.Features/Advantages of Scala:It’s general-purpose object-oriented language with functional language properties too. It’s less verbose than Java.It can work with JVM and hence is portable.It can support Java APIs comfortably.It's fast and robust in Spark context as its Spark native.It is a statically typed language.Scala supports Read-Evaluate-Print-Loop (REPL)Drawbacks / Downsides of Scala:Scala is complex to learn due to the functional nature of language.Steep learning curve.Lack of matured machine learning languages.PythonPython is one of the de-facto languages of Data Science. It is a simple, open-source, general-purpose language and is very easy to learn. It has a rich set of libraries, utilities, ready-to-use features and support to a number of mature machine learning, big data processing, visualization libraries.Advantages of Python:It is interpreted language (i.e. support to REPL, Read, Evaluate, Print, Loop.) If you type a command into a command-line interpreter and it responds immediately. Java lacks this feature.Easy to learn, easy debugging, fewer lines of code.It is dynamically typed. i.e. can dynamically defined variable types. i.e. Python as a language is type-safe.Python is platform agnostic and scalable.Drawbacks/Disadvantages:Python is slow. Big data professionals find projects built in Java / Scala are faster and robust than the once with python.Whilst using user-defined functions or third party libraries in Python with Spark, processing would be slower as increased processing is involved as Python does not have equivalent Java/Scala native language API for these functionalities.Python does not support heavy weight processing fork() using uWSGI but it does not support true multithreading.R LanguageR is the favourite language of statisticians. R is fondly called a language of statisticians.  It’s popular for research, plotting, and data analysis. Together with RStudio, it makes a killer statistic, plotting, and data analytics application.R is majorly used for building data models to be used for data analysis.Advantages/Features of R:Strong statistical modeling and visualization capabilities.Support for ‘data science’ related work.It can be integrated with Apache Hadoop and Spark easily.Drawbacks/Disadvantages of R:R is not a general-purpose language.The code written in R cannot be directly deployed into production. It needs conversion into Java or Python.Not as fast as Java / Scala.Comparison of four languages for Apache SparkWith the introduction of these 4 languages, let’s now compare these languages for the Spark framework:These languages can be categorized into 2 buckets basis high-level spark architecture support, broadly:JVM Languages: Java and ScalaNon-JVM Languages: Python and RDue to these categorizations, performance may vary. Let’s understand architecture in little depth to understand the performance implications of using these languages. This would also help us to understand the question of when to use which language.Spark Framework High-level architecture An application written in any one of the languages is submitted on the driver node and further driver node distributes the workload by dividing the execution on multiple worker nodes.JVM compatible Application Execution Flow Consider the applications written are JVM compatible (Java/Scala). Now, Spark is also written in native JVM compatible Scala language, hence there is no explicit conversion required at any point of time to execute JVM compatible applications on Spark. Also, this makes the native language applications faster to perform on the Spark framework.There are multiple scenarios for Python/R written applications:Python/R driver talk to JVM driver by socket-based API. On the driver node, both the driver processes are invoked when the application language is non-JVM language.Scenario 1: Applications for which Equivalent Java/Scala Driver API exists - This scenario executes the same way as JVM compatible applications by invoking Java API on the driver node itself. The cost for inter-process communication through sockets is negligible and hence performance is comparable. This is with the assumption that processed data over worker nodes are not to be sent back to the Driver again.Scenario 1(b): If the assumption taken is void in scenario 1 i.e. processed data on worker nodes is to be sent back to driver then there is significant overhead and serialization required. This adds to processing time and hence performance in this scenario deteriorates.Scenario 2: Applications for which Equivalent Java/Scala Driver API do not exist – Ex. UDF (User-defined functions) / Third party python libraries. In such cases equivalent Java API doesn’t exist and hence, additional executor sessions are initiated on worker node and python API is serialized on worker node and executed. This python worker processes in addition to JVM and coordination between them is overhead. Processes also compete for resources which adds to memory contention.In addition, if the data is to send back to the driver node then processing takes a lot of time and problem scales up as volume increases and hence performance is bigger problem.As we have seen a performance, Let’s see the tabular comparison between these languages.Comparison PointsJavaScalaPythonRPerformanceFasterFaster (about 10x faster than Python)SlowerSlowerLearning CurveEasier than JavaTougher than PythonSteep learning curve than Java & PythonEasiestModerateUser GroupsWeb/Hadoop programmersBig Data ProgrammersBeginners & Data EngineersData Scientists/ StatisticiansUsageWeb development and Hadoop NativeSpark NativeData Engineering/ Machine Learning/ Data VisualizationVisualization/ Data Analysis/ Statistics use casesType of LanguageObject-Oriented, General PurposeObject-Oriented & Functional General PurposeGeneral PurposeSpecifically for Data Scientists.Needs conversion into Scala/Python before productizingConcurrencySupport ConcurrencySupport ConcurrencyDoes not Support ConcurrencyNAEase of UseVerboseLesser Verbose than ScalaLeast VerboseNAType SafetyStatically typedStatically typed (except for Spark 2.0 Data frames)Dynamically TypedDynamically TypedInterpreted Language (REPL)NoNoYesYesMaturated machine learning libraries availability/ SupportLimitedLimitedExcellentExcellentVisualization LibrariesLimitedLimitedExcellentExcellentWeb Notebooks SupportIjava Kernel in Jupyter NotebookApache Zeppelin Notebook SupportJupyter Notebook SupportR NotebookWhich language is better for Spark and Why?With the info we gathered for the languages, let's move to the main question i.e. which language to choose for Spark? My answer is not a straightforward single language for this question. I will state my point of view for choosing the proper language: If you are a beginner and want to choose a language from learning Spark perspective. If you are organization/ self employed or looking to answer a question for solutioning a project perspective. I. If you are beginner:If you are a beginner and have no prior education of programming language then Python is the language for you, as it’s easy to pick up. Simple to understand and very user-friendly. It would prove a good starting point for building Spark knowledge further. Also, If you are looking for getting into roles like ‘data engineering’, knowledge of Python along with supported libraries will go a long way. If you are a beginner but have education in programming languages, then you may find Java very familiar and easy to build upon prior knowledge. After all, it grapevine of all the languages.  If you are a hardcore bigdata programmer and love exploring complexities, Scala is the choice for you. It’s complex but experts say if once you love Scala, you will prefer it over other languages anytime.If you are a data scientist, statistician and looking to work with Spark, R is the language for you. R is more science oriented than Python. II. If you are organization/looking for choice of language for implementations:You need to answer the following important questions before choosing the language:Skills and Proficiency: Which skill-sets and proficiency over language, you already have with you/in your team?Design goals and availability of features/ Capability of language: Which libraries give you better support for the type of problem(s) you are trying to solve.Performance implications Details of these explained below: 1. Skillset: This is very straightforward. Whichever is available skill set within a team, go with that to solve your problem, after evaluating answers of other two questions. If you are self-employed, the one you have proficiency is the most likely suitable choice of language.  2. Library Support:  Following gives high-level capabilities of languages:R: Good for research, plotting, and data analysis.Python: Good for small- or medium-scale projects to build models and analyse data, especially for fast start-ups or small teams.Scala/Java: Good for robust programming with many developers and teams; it has fewer machine learning utilities than Python and R, but it makes up for it with increased code maintenance.In my opinion, Scala/Java can be used for larger robust projects to ease maintenance. Also, If one wants the app to scale quickly and needs it to be robust, Scala is the choice.Python and R: Python is more universal language than R, but R is more science oriented. Broadly, one can say Python can be implemented for Data engineering use cases and R for Data science-oriented use cases. On the other hand, if you discover these two languages have about the same library support you need, then pick the one whose syntax you prefer. You may find that you need both depending on the situation. 3. Performance: As seen earlier in the article, Scala/ Java is about 10x faster than Python/R as they are JVM supported languages. However, if you are writing Python/R applications wisely (like without using UDFs/ Not sending data back to the Driver etc) they can perform equally well.ConclusionFor learning, depending upon your prior knowledge, Python is the easiest of all to pick up. For implementations, Choice is in your hands which language to choose for implementations but let me tell you one secret or a tip, you don’t have to stick to one language until you finish your project. You can divide your problem in small buckets and utilize the best language to solve the problem. This way, you can achieve balance between optimum performance, availability, proficiency in a skill, and sub-problem at hand.  Do let us know how your experience was in learning the language comparisons and the language you think is better for Spark. Moreover, which one you think is “the one for you”, through comments below.
Rated 4.5/5 based on 1 customer reviews
8239
Scala Vs Python Vs R Vs Java - Which language is b...

One of the most important decisions for the Big da... Read More

What is Context in React? How to use Context in React?

What the hack is Context?Have you ever wondered about passing data or using states in between different components without using Props? Or passing a state from Parent to Child component without manually passing a prop at every level?  Let’s understand with an example below:Here we have a parent component app.js where we have defined our states. We want to access the data of state in the last child which is “Child 1.2” in the below chart.app.js Parent ComponentThe ideal or older approach in React is to pass the data from the root component to the last component is via Props. We have to pass props in each intermediary level so as to send in the last level. While this approach also works, the real problems begin if data is needed on a different branch i.e Child 2.1 or Child 2.2 in above chart…In order to solve this problem, we need to pass data from the root/top level of the application through all the intermediate components to the one where we want to pass the data, even though some intermediate components don't even need it.  This mind-numbing process is known as prop drilling,  Prop Drillingwhere you’re passing the state from your root component to the bottom and you end up passing the data via props through components that do not even necessarily need themOne really good solution to solve the above problem is using Context According to the React documentation:  “Context provides a way to pass data through the component tree without having to pass props down manually at every level”Ordinarily, we’d have used any state management library like Redux or have used HOC’s to pass the data in a tedious manner. But what if we don’t want to use it all? Here comes the role of new Context API!In layman words, it gives an approach to make specific data available to all components throughout the React component tree regardless of how deeply nested those components are.Context is just like a global object to the subtree of the React component.When to use the Context APIThe Context API is convenient for sharing data that is either global, such as setting the header and footer theme of a website or logic of user authentication and many more. In cases like these, we can use the Context API without using any extra library or external modules. It can also be used in a multilingual application where we want to implement multiple languages that can be translated into the required text with the help of ContextAPI. It will save prop-drilling   In fact, in any situation where we have to pass a prop through a component so it reaches another component, inside down the tree is where we can use the Context API.Introducing The Context APIThe context API is a way to pass data from top component to bottom ones, without manually passing it to via props. Context is fundamentally utilized when some data needs to be accessible by numerous components at different nesting levels. To create a new Context, we can use the React createContext function like below: const MyContext = React.createContext(defaultValue);In React, data is often passed from a parent to its child component as a property. Here, we can also omit the default value which we have passed to the context, if needed.React data passing from parent to its child Let’s Get Started With ContextThree things are needed to tap into the power of context: 1. The context itselfTo create a context we can use React.createContext method which creates a context object. This is used to ensure that the components at different level can use the same context to fetch the data.   In React.createContext, we can pass an input parameter as an argument which could be anything or it can be null as well.import React from `react';  const ThemeContext = React.createContext('dark');  // Create our context        export default ThemeContext;In this example, a string is passed for the current Context which is “dark”. So we can say, the current theme required for a specific component is Dark.   Also, we have exported the object so that we can use it in other places. In one app, React also allows you to create multiple contexts. We should always try to separate context for different purposes, so as to maintain the code structure and better readability. We will see that later in our reading.   What next?? Now, to utilize the power of Context in our example, we want to provide this type of theme to all the components.  Context exposes a pair of elements which is a Provider Component and a Consumer Component.2. A context providerOkay, so now we have our Context object. And to make the context available to all our components we have to use a Provider.   But, what is Provider? According to the React documentation:"every context object comes with a Provider React component that allows consuming components to subscribe to context changes"In other words, Provider accepts a prop (value) and the data in this prop can be used in all the other child components. This value could be anything from the component state.// myProvider.js import React from 'react'; import Theme from './theme'; const myProvider = () => ( ...   ); export default myProvider;We can say that a provider acts just like a delivery service.prop finding context and deliverling it to consumerWhen a consumer asks for something, it finds it in the context and delivers it to where it's needed.But wait, who or what is the consumer???3.  A context consumer What is Consumer? A consumer is a place to keep the stored information. It can request for the data using the provider and can even manipulate the global store if the provider allows it. In our previous example, let’s grab the theme value and use it in our Header component. // Header.js   import React from 'react'; import Theme from './theme';   const Header = () => (                        {theme => Selected theme is {theme}}             );   export default Header;Dynamic Context:   We can also change the value of the provider by simply providing a dynamic context. One way of achieving it is by placing the Provider inside the component itself and grabbing the value from component state as below:// Footer.js   import React from 'react';   class Footer extends React.Component {    state = {        theme: 'dark'    };      render() {        return (                                                );    } }Simple, no? We can easily change the value of  the Provider to any Consumer.Consuming Context With Class-based ComponentsWe all pretty know that there are two methods to write components in React, which is Class based components and Function based components. We have already seen a demo of how we can use the power of Context in class based components.  One is to use the context from Consumer like “ThemeContext.Consumer” and the other method is by assigning context object from current Context to contextType property of our class.import React, { Component } from "react"; import MyThemeContext from "../Context/MyThemeContext"; import GlobalTheme from "../theme";   class Main extends Component {    constructor() {        super();    }    static contextType = MyThemeContext;  //assign context to component    render() {        const currentTheme = GlobalTheme[this.context];        return (            ...        );    }   }There is always a difference in how we want to use the Context. We can either provide it outside the render() method or use the Context Consumer as a component itself.  Here in the above example, we have used a static property named as contextType which is used to access the context data. It can be utilized by using this.context. This method however, limits you consuming, only one context at a time.Consuming Context With Functional ComponentsContext with Functional based components is quite easy and less tedious. In this we can access the context value through props with the help of useContext method in React. This hook (useContext) can be passed in as the argument along with our Context to consume the data in the functional component.const value = useContext(MyContext);It accepts a context object and returns the current context value. To read more about hooks, read here.  Our previous example looks like:import React, { useContext } from 'react' import MyThemeContext from './theme-context'   const User = props => {    const context = useContext(MyThemeContext)    return ...Now, instead of wrapping our content in a Consumer component we have access to the theme context state through the ‘context’ variable.But we should avoid using context for keeping the states locally. Instead of  conext, we can use local state there.Use of Multiple ContextsIt may be possible that we want to add multiple contexts in our application. Like holding a theme for the entire app, changing the language based on the location, performing some A/B testing, using global parameters for login or user Profile… For instance, let’s say there is a requirement to keep both Theme context and userInfo Context, the code will look like as:       ...   It’s quite possible in React to hold multiple Contexts, but this definitely hampers rendering, serving ‘n’ number of contexts in ‘m’ component and holding the updated value in each rendered component.To avoid this and to make re-rendering faster, it is suggested to make each context consumer in the tree as a separate node or into different contexts.                 And we can perform the nesting in context as:    {theme => (                    {colour => (                Theme: {theme} and colour: {colour}            )}            )} It’s worth noting that when a value of a context changes in the parent component, the child components or the components’ holding that value should be rerendered or changed. Hence, whenever there is a change in the value of provider, it will cause its consumers to re-render.ConclusionDon’t you think this concept is just amazing?? Writing a global context like theme or language or userProfile and using the data of them directly in the child or other components? Implementing these stateful logic by global preferences was never so easy, but Context made this transportation job a lot simple and achievable! Hope you find this article useful. Happy Coding!Having challenge learning to code? Let our experts help you with customized courses!
Rated 4.0/5 based on 1 customer reviews
7926
What is Context in React? How to use Context in Re...

What the hack is Context?Have you ever wondered ab... Read More

How to use sys.argv in Python

The sys module is one of the common and frequently used modules in Python. In this article, we will walk you through how to use the sys module. We will learn about what argv[0] and sys.argv[1] are and how they work. We will then go into how to parse Command Line options and arguments, the various ways to use argv and how to pass command line arguments in Python 3.x In simple terms,Command Line arguments are a way of managing the script or program externally by providing the script name and the input parameters from command line options while executing the script. Command line arguments are not specific just to Python. These can be found in other programming languages like C, C# , C++, PHP, Java, Perl, Ruby and Shell scripting. Understanding sys.argv with examples  sys.argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments. Let us take a closer look with a few examples. With the len(sys.argv) function, you can count the number of arguments. import sys print ("Number of arguments:", len(sys.argv), "arguments") print ("Argument List:", str(sys.argv)) $ python test.py arg1 arg2 arg3 Number of arguments: 4 arguments. Argument List: ['test.py', 'arg1', 'arg2', 'arg3']Module name to be used while using sys.argv To use sys.argv, you will first need to the sys module. What is argv[0]? Remember that sys.argv[0] is the name of the script. Here – Script name is sysargv.py import sys print ("This is the name of the script: ", sys.argv[0]) print ("Number of arguments: ", len(sys.argv)) print ("The arguments are: " , str(sys.argv))Output:This is the name of the script:  sysargv.py                                                                               Number of arguments:  1                                                                                                 The arguments are:  ['sysargv.py']What is "sys. argv [1]"? How does it work? When a python script is executed with arguments, it is captured by Python and stored in a list called sys.argv. So, if the below script is executed: python sample.py Hello Python Then inside sample.py, arguments are stored as: sys.argv[0] == ‘sample.py’ sys.argv[1] == ‘Hello’ sys.argv[2] == ‘Python’Here,sys.argv[0] is always the filename/script executed and sys.argv[1] is the first command line argument passed to the script . Parsing Command Line options and arguments  Python provides a module named as getopt which helps to parse command line options and arguments. Itprovides a function – getopt, whichis used for parsing the argument sequence:sys.argv. Below is the syntax: getopt.getopt(argv, shortopts, longopts=[]) argv: argument list to be passed.shortopts: String of short options as list . Options in the arguments should be followed by a colon (:).longopts: String of long options as list. Options in the arguments should be followed by an equal sign (=). import getopt import sys   first ="" last ="" argv = sys.argv[1:] try:     options, args = getopt.getopt(argv, "f:l:",                                ["first =",                                 "last ="]) except:     print("Error Message ")   for name, value in options:     if name in ['-f', '--first']:         first = value     elif name in ['-l', '--last']:         last = value   print(first + " " + last)Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py -f Knowledge -l Hut Knowledge Hut (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py --first Knowledge –last Hut Knowledge HutWhat are command line arguments? Why do we use them? Command line arguments are parameters passed to a program/script at runtime. They provide additional information to the program so that it can execute. It allows us to provide different inputs at the runtime without changing the code. Here is a script named as argparse_ex.py: import argparse parser = argparse.ArgumentParser() parser.add_argument("-n", "--name", required=True) args = parser.parse_args() print(f'Hi {args.name} , Welcome ')Here we need to import argparse package Then we need to instantiate the ArgumentParser object as parser. Then in the next line , we add the only argument, --name . We must specify either shorthand (-n) or longhand versions (--name)  where either flag could be used in the command line as shown above . This is a required argument as mentioned by required=True Output:  (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name Nandan  Hi Nandan , Welcome  (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py -n Nandan  Hi Nandan , Welcome The example above must have the --name or –n option, or else it will fail.(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name   usage: argparse_ex.py [-h] --name NAME argparse_ex.py: error: the following arguments are required: --namePassing command line arguments in Python 3.x argv represents an array having the command line arguments of thescript . Remember that here, counting starts fromzero [0], not one (1). To use it, we first need to import sys module (import sys). The first argument, sys.argv[0], is always the name of the script and sys.argv[1] is the first argument passed to the script. Here, we need to slice the list to access all the actual command line arguments. import sys if __name__ == '__main__':     for idx, arg in enumerate(sys.argv):        print("Argument #{} is {}".format(idx, arg))     print ("No. of arguments passed is ", len(sys.argv))Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python argv_count.py Knowledge Hut 21 Argument #0 is argv_count.py Argument #1 is Knowledge Argument #2 is Hut Argument #3 is 21 No. of arguments passed is  4Below script - password_gen.py is used to generate a secret password by taking password length as command line argument.import secrets , sys, os , string ''' This script generates a secret password using possible key combinations''' ''' Length of the password is passed as Command line argument as sys.argv[1]''' char = string.ascii_letters+string.punctuation+string.digits length_pwd = int(sys.argv[1])   result = "" for i in range(length_pwd):     next= secrets.SystemRandom().randrange(len(char))     result = result + char[next] print("Secret Password ==" ,result,"\n")Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python password_gen.py 12 Secret Password == E!MV|,M][i*[Key takeaways Let us summarize what we've learnt so far. We have seen how to use the sys module in Python, we have looked at what areargv[0] and sys.argv[1] are and how they work, what Command Line arguments are and why we use them and how to parse Command Line options and arguments. We also dived into multiple ways to use argv and how to pass command line arguments in Python 3.xHope this mini tutorial has been helpful in explaining the usage of sys.argv and how it works in Python. Be sure to check out the rest of the tutorials on KnowledgeHut’s website and don't forget to practice with your code! 
Rated 4.0/5 based on 14 customer reviews
5985
How to use sys.argv in Python

The sys module is one of the common and frequently... Read More

20% Discount