How this set is put together
Questions 1โ38 are hands-on coding exercises โ the kind you're expected to write on a whiteboard or in a shared editor. 39โ40 are quick concept checks. 41โ50 shift into applied Python on Google Cloud, aimed at a data-engineering-flavored interview rather than general Python.
Original numbering is kept as the Q label on each item so it still maps back to the source sheet.
Sections 8โ10 (Q51 onward) are additional questions, not part of the original PDF โ written to extend the same worksheet into AWS, Azure, and Snowflake, since the source material already leaned into cloud data engineering from Q41 onward.
Strings
Reversal, counting, comparison โ the bread-and-butter string manipulation questions almost every interview opens with.
- Q1Write a program that reverses a string entered by the user.
Hint
Python strings support slicing with a negative step:s[::-1]reverses in one line. Know how to do it manually with a loop too โ interviewers often ask for both. - Q3Check whether a string is a palindrome.
Hint
Compare the string to its own reverse:s == s[::-1]. Decide up front whether to ignore case and spaces. - Q6Count how many times a given character appears in a string.
Hint
s.count(char)does this directly โ but be ready to also show the manual loop-and-counter version. - Q13Write a function that checks whether one string is an anagram of another.
Hint
Two clean approaches: sort both strings and compare (sorted(a) == sorted(b)), or compare character counts withcollections.Counter. Watch for spaces and letter case. - Q17Remove all vowels from a string.
- Q21Reverse the order of words in a sentence โ word-level, not character-level.
Hint
Split on spaces, reverse the resulting list, then join back:' '.join(s.split()[::-1]). Don't confuse this with Q1's character reversal. - Q22Check whether a string has all unique characters (no repeats).
Hint
If every character is unique, converting to asetwon't lose any โ solen(set(s)) == len(s)answers it in one line. - Q30Count the number of vowels in a string.
- Q32Check whether a string contains only digits.
Hint
Python has a built-in for exactly this:s.isdigit(). - Q33Write a function that strips punctuation marks out of a string.
Hint
Thestringmodule has a ready-madestring.punctuationconstant โ filter any character that appears in it out of your string.
Numbers & Math
Factorials, primes, digit manipulation โ questions that test loops and basic number theory rather than data structures.
- Q2Find the factorial of a number entered by the user.
Hint
A simple loop multiplying 1..n works, ormath.factorial(n)if the interviewer allows library functions. Remember 0! = 1. - Q8Check whether a number is prime.
Hint
You only need to test divisors up tosqrt(n), not all the way to n โ that's the optimization interviewers usually want to see you mention. - Q12Find the sum of the digits of a number.
Hint
Repeatedly taken % 10to peel off the last digit, thenn //= 10to drop it, until n is 0. - Q20Write a method to calculate x raised to the power n (x^n).
Hint
x ** nis the built-in operator. If asked to implement it yourself, look at fast exponentiation (repeated squaring) rather than a simple loop โ it's the follow-up question waiting to happen. - Q29Write a function to check whether a number is a perfect number.
Hint
A perfect number equals the sum of its proper divisors (e.g. 6 = 1+2+3). Loop from 1 to n-1, sum the divisors of n, and compare. - Q34Check whether a number is an Armstrong number (the sum of its digits, each raised to the power of the digit count, equals the number itself).
Hint
First count the digits (len(str(n))), then for each digit computedigit ** digit_countand sum them. Example: 153 โ 1ยณ+5ยณ+3ยณ = 153.
Lists, Dicts & Data Structures
Finding, merging, and de-duplicating across lists and dictionaries โ where knowing the right built-in usually beats writing a manual loop.
- Q4Find the largest element in a user-entered list.
- Q5Remove duplicates from a list. Example:
lst = [1,2,3,1,2,3,4,5,9,3,1].Hint
Converting to asetis the fast one-liner, but sets don't preserve order โ if order matters, build a new list while checking membership, or usedict.fromkeys(lst). - Q9Merge two already-sorted lists into a single sorted list.
Hint
sorted(a + b)works but ignores that both inputs are already sorted. The "proper" answer walks both lists with two pointers, taking the smaller front element each time โ the classic merge step from merge sort. - Q10Find the elements common to two lists.
Hint
Set intersection is the direct route:set(a) & set(b). - Q11Find the missing number in a sequence of numbers.
Hint
If it's 1..n with one missing, the expected sum isn*(n+1)/2โ subtract the actual sum from that to get the missing value in one pass. - Q15Find the duplicate values in a list.
Hint
collections.Counter(lst)gives you a count per element โ filter for counts greater than 1. - Q16Count how many times each element appears in a list.
- Q18Find the intersection (common elements) of two lists.
- Q19Find the nth largest element in a list.
Hint
Sort descending and index:sorted(lst, reverse=True)[n-1]. Ask whether duplicate values should count as separate ranks or be collapsed first. - Q23Write a function that returns the most frequent element in a list.
Hint
collections.Counter(lst).most_common(1)hands you the answer directly. - Q26Merge two dictionaries in Python.
Hint
Modern Python:merged = d1 | d2(3.9+), or{**d1, **d2}on older versions. Know what happens to keys that exist in both โ the second dict wins. - Q28Find the second largest number in a list.
Hint
The trap is duplicate max values โ sort and dedupe first (sorted(set(lst))) before picking the second-from-last, unless the question wants duplicates counted. - Q31Find the sum of all elements across a list of lists.
Hint
A nested loop works, or flatten first with a list comprehension:sum(x for sub in lists for x in sub).
Algorithms & Logic Puzzles
The three questions on this sheet that go beyond "loop over a collection" into actual algorithmic thinking.
- Q7Generate the Fibonacci sequence up to the nth term as a list. Example: if n = 5, the output is
[0, 1, 1, 2, 3].Hint
Start with[0, 1]and keep appending the sum of the last two, stopping once the list has n items. Watch the edge cases n=0 and n=1 โ the example above shows n=5 producing 5 terms, not 6. - Q14Convert a string to an integer, handling any errors that occur.
Hint
Wrapint(s)in atry/except ValueErrorblock โ that's the whole exercise, but interviewers are checking that you reach for exception handling instead of manually validating characters. - Q24Find the longest substring without repeating characters.
Hint
This is the sliding-window classic. Keep a window [left, right] and a set of characters currently in it; when you hit a repeat, shrink from the left until the duplicate is gone, tracking the max window size as you go. - Q25Implement a basic calculator supporting addition, subtraction, multiplication, and division.
Hint
Start simple: a function that takes two numbers and an operator string, dispatches with if/elif (or a dict of operator โ function). Don't forget to guard against division by zero. - Q27Check whether a given string of parentheses is validly balanced.
Hint
Classic stack problem: push opening brackets, and on a closing bracket, pop and check it matches. If you ever pop from an empty stack, or anything's left on the stack at the end, it's invalid.
Loops & Pattern Printing
Nested-loop exercises that test whether you can control row and column logic independently โ a staple of campus-style interviews.
- Q35Perform matrix multiplication.
Hint
Three nested loops: for each row of A and column of B, sum the products of matching elements. Confirm the inner dimensions match (columns of A = rows of B) before you start. - Q36Print the multiplication table for a number.
- Q37Print a right-angled triangle and a left-angled triangle of stars.
Hint
Right-angled: printistars on rowi. Left-angled: pad each row with spaces before the stars so the triangle leans the other way โ(rows-i)spaces thenistars. - Q38Print each of these five patterns for n rows:
1. 2. 3. 4. 5. * ***** 1 1 * ** ***** 12 22 ** *** ***** 123 333 *** **** ***** 1234 4444 ****
Hint
Same nested-loop skeleton for all five โ only what you print on the inner loop changes: a fixed*, a full row of stars regardless of row number, the running column index, or the row number repeated. Write the outer "for each row" loop once and swap the inner print logic per pattern.
Core Language Concepts
Two short conceptual questions โ no coding, just clear explanations.
- Q39What's the difference between
returnandyield?Hint
returnexits the function and hands back one value, ending execution.yieldpauses the function and hands back one value at a time, resuming right where it left off on the next call โ that's what makes a function a generator. - Q40What's the difference between call-by-value and call-by-reference?
Hint
Explain the general concept, then note the twist: Python is technically neither โ it's "call by object reference." Mutable objects (lists, dicts) can be changed in place through the reference; reassigning the parameter itself never affects the caller's variable.
Python on GCP / Data Engineering
The sheet shifts here from generic Python to applied questions about using Python with Google Cloud services โ BigQuery, Cloud Storage, Dataflow, Pub/Sub, and Cloud Functions. These are mostly "explain your approach" rather than "write the code."
- Q41How do you handle large datasets in Python when working with GCP services like BigQuery or Cloud Storage?
Hint
Talk about avoiding loading everything into memory at once โ reading in chunks/batches, using BigQuery's own query engine to do heavy aggregation server-side rather than pulling raw rows into Python, and streaming reads from Cloud Storage instead of downloading whole files. - Q42Write a Python script to read a CSV file from Google Cloud Storage and load it into BigQuery.
Hint
Two client libraries are the answer:google-cloud-storageto read/download the object, andgoogle-cloud-bigquery'sload_table_from_uri(which can load directly from ags://path without you touching the bytes yourself) orload_table_from_file. - Q43How would you optimize a Python script that processes data in parallel on Google Cloud Dataflow?
Hint
This is really an Apache Beam question โ Dataflow runs Beam pipelines. Mention avoiding data skew across workers, tuning worker count/machine type, using combiners instead of grouping everything before aggregating, and minimizing expensive per-element operations. - Q44Explain how you'd use Python to automate the deployment of a data pipeline on GCP (e.g., using Cloud Composer).
Hint
Cloud Composer is managed Apache Airflow โ a pipeline here means writing a Python DAG file defining tasks and dependencies, which Composer schedules and runs. - Q45How do you handle missing or corrupted data in a dataset using Python before loading it into BigQuery?
Hint
This is a pandas data-cleaning question in disguise:isnull()/dropna()/fillna()for missing values, type validation and try/except for malformed rows, and deciding whether to drop, impute, or flag bad records before the load step. - Q46Write a Python function to query data from BigQuery and perform a transformation (e.g., aggregation or filtering).
Hint
bigquery.Client().query(sql).to_dataframe()gets you the results as a pandas DataFrame โ then the "transformation" can be either SQL in the query itself, or pandas operations afterward. Be ready to justify which one you'd pick and why. - Q47How would you monitor and log errors in a Python-based data pipeline running on GCP?
Hint
Point at Cloud Logging (via thegoogle-cloud-loggingclient, or just structured stdout logging which GCP auto-captures) and Cloud Monitoring for alerting โ plus wrapping pipeline steps in try/except with meaningful log messages rather than letting failures fail silently. - Q48Explain how to use Python to interact with GCP's Pub/Sub for real-time data streaming.
Hint
Thegoogle-cloud-pubsublibrary has two sides: aPublisherClientto publish messages to a topic, and aSubscriberClientthat pulls (or gets pushed) messages from a subscription and acknowledges them once processed. - Q49How do you ensure data security and compliance when using Python to process data on GCP?
Hint
Talk about IAM roles scoped to least privilege, never hardcoding credentials (use service accounts / Application Default Credentials), encrypting data at rest and in transit (GCP does this by default, but note it), and tools like Cloud DLP for sensitive-data scanning. - Q50Write a Python script to schedule and trigger a Cloud Function that processes data from a Cloud Storage bucket.
Hint
Two separate pieces: the Cloud Function itself (a Python function with a Storage-triggered signature, deployed viagcloud functions deploy --trigger-bucket), and if you want it on a schedule rather than triggered by uploads, pairing it with Cloud Scheduler to invoke it periodically.
Python on AWS
Boto3, S3, Lambda, Glue, Redshift, and the rest of the AWS data-engineering toolkit as it shows up in Python interviews.
- Q51How do you use Boto3 to interact with S3 buckets in Python?
Hint
boto3.client('s3')orboto3.resource('s3')are the two entry points โ client gives you low-level API calls (put_object,get_object,list_objects_v2), resource gives you a more Pythonic object model. Know when you'd reach for each. - Q52Write a Python script to upload a local file to an S3 bucket.
Hint
s3.upload_file(local_path, bucket, key)is the one-liner โ it also handles multipart upload for large files automatically, which is worth mentioning. - Q53How would you read a CSV file from S3 into a pandas DataFrame without downloading it to disk first?
Hint
Read the object into memory withget_object()and wrap the body bytes inio.BytesIObefore handing it topd.read_csvโ or let pandas do it directly viapd.read_csv('s3://bucket/key.csv')ifs3fsis installed. - Q54Explain how a Python AWS Lambda function is structured โ the handler signature, the event object, and the context object.
Hint
Every handler looks likedef handler(event, context):.eventcarries whatever triggered the function (an S3 notification, an API Gateway request, etc.);contextcarries runtime info like the remaining execution time and request ID. - Q55How do you manage credentials securely in a Python app running on AWS, instead of hardcoding access keys?
Hint
IAM roles attached to the compute resource (EC2 instance profile, Lambda execution role) let Boto3 pick up temporary credentials automatically โ no keys in code at all. For local dev, named profiles in~/.aws/credentialsplus environment variables, never committed secrets. - Q56Write a Python function that publishes a message to an SQS queue, and another that polls and processes messages from it.
Hint
sqs.send_message(QueueUrl=..., MessageBody=...)to publish;sqs.receive_message(QueueUrl=..., MaxNumberOfMessages=...)to poll, thendelete_messageafter successful processing so it doesn't get redelivered. - Q57How would you use Python with AWS Glue to build an ETL job?
Hint
Glue jobs run PySpark (or plain Python shell jobs for lighter workloads) using theawsgluelibrary'sGlueContextandDynamicFrameโ Glue also auto-generates a starting script from its Data Catalog schema, which you then customize. - Q58Explain how to connect to and query an Amazon Redshift cluster using Python.
Hint
redshift_connectoror apsycopg2-based connection (Redshift speaks the Postgres wire protocol) both work โ or go through SQLAlchemy for ORM-style access. Mention IAM-based authentication as the more secure alternative to a static password. - Q59How do you handle retries and throttling errors (like
ClientErrorwith a throttling code) when calling AWS APIs from Boto3?Hint
Boto3 already retries transient errors by default (configurable retry mode), but for custom logic, catchbotocore.exceptions.ClientError, inspecte.response['Error']['Code'], and back off exponentially on throttling-related codes. - Q60Write a Python Lambda function that's triggered by a new file landing in an S3 bucket.
Hint
The event dict for an S3 trigger containsevent['Records'][0]['s3']['bucket']['name']and['object']['key']โ pull those out to know which file to process. - Q61How would you use Python to publish custom metrics or logs to CloudWatch?
Hint
boto3.client('cloudwatch').put_metric_data(...)for custom metrics; for logs, anything printed to stdout inside a Lambda is automatically captured by CloudWatch Logs โ no extra setup needed there. - Q62What's the difference between using Lambda layers versus bundling all dependencies directly into your deployment package?
Hint
Layers are shared, versioned dependency bundles you attach to multiple functions โ useful for a common library (like pandas) reused across several Lambdas, keeping each function's own deployment package small. - Q63How do you use Python with AWS Step Functions to orchestrate a multi-step workflow?
Hint
Step Functions itself is defined in Amazon States Language (JSON), not Python โ but each state typically invokes a Python Lambda. From Python you'd use Boto3'sstepfunctionsclient to start executions and check their status programmatically. - Q64Write a Python script that uploads a file to S3 with server-side encryption enabled.
Hint
PassExtraArgs={'ServerSideEncryption': 'AES256'}(or'aws:kms'with a key ID) toupload_file. - Q65How would you paginate through a large S3 bucket listing or DynamoDB scan using Boto3's paginators?
Hint
Boto3 has a built-inget_paginator('list_objects_v2')(or'scan'for DynamoDB) that yields pages automatically, instead of you manually tracking aNextToken/LastEvaluatedKeyacross calls.
Python on Azure
Blob Storage, Azure Functions, Data Factory, Databricks, and Key Vault โ the Azure equivalents of the AWS and GCP questions above.
- Q66How do you use the Azure SDK for Python to interact with Blob Storage?
Hint
Theazure-storage-blobpackage'sBlobServiceClientis the entry point โ from it you get aContainerClient, then aBlobClientfor individual blobs, with methods likeupload_blobanddownload_blob. - Q67Write a Python script to upload a file to an Azure Blob Storage container.
Hint
blob_client.upload_blob(data, overwrite=True)after opening the local file in binary mode and passing its contents asdata. - Q68How would you authenticate a Python application to Azure โ Service Principal versus Managed Identity?
Hint
A Service Principal is an app identity with a client ID/secret you manage yourself, useful outside Azure. Managed Identity lets a resource running inside Azure (like a VM or Function) authenticate with no credentials in code at all โ prefer it whenever the workload already runs on Azure. - Q69Explain how a Python Azure Function is structured โ triggers, bindings, and the function signature.
Hint
A trigger decides what invokes the function (HTTP request, blob upload, timer); bindings are declarative input/output connections to other services, configured either infunction.jsonor via decorators in the newer Python programming model. - Q70How do you use Python within Azure Data Factory โ for example, via a Databricks notebook activity โ to transform data?
Hint
ADF itself is a low-code orchestrator; the actual Python/PySpark transformation logic usually lives in a Databricks notebook that ADF's pipeline invokes as one activity in a larger workflow. - Q71Write a Python script to query data from Azure Synapse Analytics.
Hint
pyodbcwith the Synapse SQL endpoint connection string is the classic route, orsqlalchemywith a matching connector โ the query pattern is the same as any SQL-over-ODBC connection. - Q72How would you use PySpark within Azure Databricks to process large datasets?
Hint
Databricks notebooks come with a pre-configuredsparksession โ you read data into a Spark DataFrame (spark.read.format(...)), transform it with Spark's distributed operations, and write results back out, letting the cluster parallelize the work rather than pandas on a single node. - Q73How do you store and retrieve secrets, like connection strings, securely using Azure Key Vault from Python?
Hint
Theazure-keyvault-secretslibrary'sSecretClient, authenticated viaDefaultAzureCredential(which picks up Managed Identity automatically when running in Azure), fetches secrets by name at runtime instead of storing them in config files. - Q74Explain how to set up a Python Azure Function that's triggered by a new blob upload.
Hint
A blob-triggered function declares the container path pattern to watch (e.g.samples-workitems/{name}) in its binding config โ Azure invokes the function automatically whenever a matching blob is created or updated. - Q75How would you use Python's
azure-eventhublibrary to consume streaming events from Azure Event Hubs?Hint
AnEventHubConsumerClientsubscribes to a consumer group and calls your callback function for each batch of events received โ conceptually the Azure equivalent of consuming from AWS Kinesis or GCP Pub/Sub. - Q76How do you handle logging and monitoring for a Python app in Azure using Application Insights?
Hint
Theopencensus-ext-azure(or newer Azure Monitor OpenTelemetry) package plugs into Python's standardloggingmodule and ships log records, exceptions, and custom telemetry to Application Insights without changing how you write log statements. - Q77Write a Python function to copy data between two Azure Storage containers.
Hint
You don't need to download and re-upload โblob_client.start_copy_from_url(source_blob_url)tells Azure to copy the blob server-side. - Q78What changed between the
azure-storage-blobSDK v2 and v12, and why does it matter for existing code?Hint
v12 was a ground-up rewrite with a different client model (BlobServiceClient/ContainerClient/BlobClientinstead of the older singleBlockBlobService) and different method names โ code written for v2 won't run unmodified against v12, which matters when maintaining or upgrading legacy pipelines. - Q79How would you schedule a recurring Python data job in Azure โ Azure Functions Timer trigger versus Data Factory pipeline schedule?
Hint
A Timer-triggered Function is lightweight and code-first (a CRON expression drives a Python function directly); a Data Factory schedule trigger fires a whole pipeline, better suited when the "job" is really a multi-step orchestration rather than one script.
Python & Snowflake
Connecting to Snowflake, moving data in and out, and using Snowpark to push DataFrame-style logic into the warehouse itself.
- Q80How do you connect to Snowflake from Python using
snowflake-connector-python?Hint
snowflake.connector.connect(user=..., password=..., account=..., warehouse=..., database=..., schema=...)returns a connection you can open a cursor on and run SQL through, much like any DB-API-compliant driver. - Q81Write a Python script to run a query against Snowflake and load the results into a pandas DataFrame.
Hint
The connector ships a helper for exactly this:cursor.execute(sql); df = cursor.fetch_pandas_all()โ faster than manually looping over fetched rows. - Q82How would you use Snowpark for Python to perform DataFrame-style transformations that actually execute inside Snowflake?
Hint
Snowpark's DataFrame API looks like pandas/PySpark, but it builds up a query lazily and pushes execution down to Snowflake's own compute when you call an action like.collect()โ the data never leaves the warehouse until you ask for results. - Q83Explain how to bulk-load data into Snowflake from Python โ for example, using
COPY INTOafter staging a file.Hint
The pattern is:PUTthe local file onto a Snowflake stage (internal or an external S3/Blob stage), then run aCOPY INTO table FROM @stageSQL command โ both issued from Python via the connector's cursor. - Q84How do you manage Snowflake connection credentials securely in a Python application โ key-pair authentication versus password?
Hint
Key-pair auth (an RSA key registered against the Snowflake user) avoids storing a plaintext password and is the recommended approach for service accounts and automated pipelines; combine it with a secrets manager rather than embedding the key in code. - Q85Write a Python function that creates a temporary Snowflake stage, uploads a local file to it, and loads it into a table.
Hint
Three SQL statements run through your cursor in sequence:CREATE TEMPORARY STAGE,PUT file://... @stage, thenCOPY INTO table FROM @stage. - Q86How would you use Python to call a Snowflake stored procedure or user-defined function (UDF)?
Hint
From the connector, it's just SQL:cursor.execute("CALL my_procedure(%s)", (arg,)). Snowpark also lets you register and call Python UDFs/stored procedures directly from your Python session. - Q87Explain how to handle Snowflake's auto-suspend / auto-resume warehouse behavior when running long Python jobs.
Hint
A warehouse auto-suspends after a configurable idle period to save cost, then auto-resumes (with a brief cold-start delay) on the next query โ a long-running Python job should expect and tolerate that startup latency on its first query rather than treating it as an error. - Q88How do you use Python to monitor and optimize Snowflake query performance โ for example, via
QUERY_HISTORY?Hint
Query Snowflake's ownSNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY(orINFORMATION_SCHEMA.QUERY_HISTORY) view like any other table from Python, then look at execution time, bytes scanned, and warehouse size to spot slow or overprovisioned queries. - Q89Write a Python script that uses Snowflake Streams and Tasks to process only newly changed rows in a table.
Hint
A Stream tracks row-level changes (inserts/updates/deletes) on a table since it was last consumed; a Task runs on a schedule and typically doesINSERT INTO target SELECT * FROM stream_name, which both processes the changes and clears the stream in one step โ this is Snowflake's native CDC pattern. - Q90How would you handle Snowflake's semi-structured data types (VARIANT, JSON) when querying from Python?
Hint
Snowflake returns VARIANT columns as JSON strings through the connector โ parse them with Python'sjsonmodule, or better, flatten the structure in SQL first using:field_namepath notation orFLATTEN()before it ever reaches Python. - Q91What's the difference between using
snowflake-connector-pythondirectly versus SQLAlchemy's Snowflake dialect from Python?Hint
The raw connector gives you direct SQL/cursor control and Snowflake-specific features (likefetch_pandas_all); the SQLAlchemy dialect trades some of that for ORM compatibility and a database-agnostic interface, handy when a codebase needs to support multiple backends through one abstraction.