LearnFrenzy
Sign in Take a free test

Python Programming interview · Set 1 of 19

Python Basics and Data Types

  • 5 follow-up questions
  • 4 key points
  • Code examples
Test yourself

The Python fundamentals interviewers test

Most Python bugs come from misunderstanding names and mutability. Show you know how variables point to objects, which types are mutable, and which built-in collection fits each job.

  • Data modelNames, objects and mutability.
  • Collectionslist, tuple, dict, set and collections.
  • IdiomsComprehensions, *args/**kwargs and copies.

Python looks simple, which is exactly why interviewers dig into the details: what is mutable, how variables really work, and which built-in data structure fits a job. Clear answers here show you write Python, not just Java with fewer semicolons.

1. List vs tuple — what is the difference?

Lists are mutable (you can add, remove and change items); tuples are immutable. Because tuples cannot change, they are hashable when their items are, so they can be dictionary keys or set members, and they signal “this is a fixed record”, such as a coordinate.

point = (12.97, 77.59)          # fixed record: latitude, longitude
visited = {point}               # tuples can go in a set
cart = ["pen", "book"]
cart.append("bag")              # lists grow and change

2. Explain mutable vs immutable objects with an example.

Immutable objects (int, str, tuple, frozenset) cannot change; “modifying” creates a new object. Mutable objects (list, dict, set) change in place, and every name pointing to them sees the change.

a = [1, 2]
b = a            # both names point to the same list
b.append(3)
print(a)         # [1, 2, 3]

s = "hi"
t = s
t += "!"         # new string object; s is unchanged
print(s)         # hi

3. What is the mutable default argument trap?

Default values are evaluated once, when the function is defined. A mutable default such as a list is shared across calls and keeps growing. Use None and create the list inside.

def add_item(item, bucket=[]):      # bug: one list shared by every call
    bucket.append(item)
    return bucket

def add_item_fixed(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

4. What is the difference between is and ==?

== compares values; is checks whether two names point to the same object. Use is only for singletons such as None: if x is None. Small integers and some strings are cached, so is may accidentally appear to work — never rely on that.


5. How do dictionaries work and what can be a key?

A dict is a hash table with average O(1) lookup, and since Python 3.7 it keeps insertion order. Keys must be hashable — immutable types like str, int or tuples of immutables. Useful helpers: get() with a default, setdefault(), collections.Counter and defaultdict.

from collections import Counter, defaultdict

words = "to be or not to be".split()
print(Counter(words).most_common(2))     # [('to', 2), ('be', 2)]

by_dept = defaultdict(list)
for name, dept in [("Asha", "HR"), ("Ravi", "IT"), ("Meera", "IT")]:
    by_dept[dept].append(name)

6. What are list, dict and set comprehensions?

A compact, readable way to build a collection from another iterable, often faster than an explicit loop. Keep them short — if it needs two conditions and nested loops, a normal loop is clearer.

squares = [n * n for n in range(10) if n % 2 == 0]
price_of = {p["sku"]: p["price"] for p in products}
domains = {email.split("@")[1] for email in emails}

7. Explain *args and **kwargs.

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They are used to write flexible functions and to forward arguments to another function, as decorators do.

def log_call(func_name, *args, **kwargs):
    print(func_name, args, kwargs)

log_call("transfer", 500, "INR", to="Ravi", note="rent")
# transfer (500, 'INR') {'to': 'Ravi', 'note': 'rent'}

8. Shallow copy vs deep copy?

A shallow copy creates a new outer container but shares the inner objects; a deep copy copies everything recursively. It matters for nested lists and dicts.

import copy

grid = [[0, 0], [0, 0]]
shallow = copy.copy(grid)
deep = copy.deepcopy(grid)
grid[0][0] = 9
print(shallow[0][0], deep[0][0])   # 9 0

Remember

Key points

  • Defaults are evaluated once

    Never use a mutable default argument.

  • is for None only

    == for values, is for identity.

  • Dicts keep insertion order

    Guaranteed since Python 3.7.

  • Nested data needs deepcopy

    Shallow copies share inner objects.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 How do you swap two variables in Python? Basic

    a, b = b, a — tuple packing and unpacking, no temporary variable needed.

  2. 2 What do enumerate() and zip() do? Basic

    enumerate gives (index, item) pairs; zip walks several iterables together.

    for i, (name, score) in enumerate(zip(names, scores), start=1):
        print(i, name, score)
  3. 3 Why are strings immutable in Python? Intermediate

    It makes them hashable (usable as dict keys), safe to share and cacheable. Build long strings with "".join(parts) instead of repeated +=.

  4. 4 What is the difference between remove(), pop() and del? Intermediate

    remove(x) deletes the first matching value; pop(i) removes by index and returns it; del lst[i] removes by index or slice without returning.

  5. 5 How do you merge two dictionaries? Intermediate

    Use a | b (Python 3.9+) for a new dict, or a |= b to update in place. Keys in b win.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links