<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dipayan Nandi on Medium]]></title>
        <description><![CDATA[Stories by Dipayan Nandi on Medium]]></description>
        <link>https://medium.com/@ark4nandi?source=rss-2ecdb1cc6e98------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*74CSRQgwBKaCLtjb</url>
            <title>Stories by Dipayan Nandi on Medium</title>
            <link>https://medium.com/@ark4nandi?source=rss-2ecdb1cc6e98------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:46:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ark4nandi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Technical Guide to LangChain + LangGraph]]></title>
            <link>https://medium.com/@ark4nandi/technical-guide-to-langchain-langgraph-5f64f985e169?source=rss-2ecdb1cc6e98------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f64f985e169</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Dipayan Nandi]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 18:12:31 GMT</pubDate>
            <atom:updated>2026-04-13T18:12:31.563Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction to LangChain</h3><h3>What is LangChain?</h3><p>LangChain is a framework for building applications powered by <strong>Large Language Models (LLMs)</strong> by enabling:</p><ul><li>Structured workflows (chains)</li><li>Tool integration (APIs, functions)</li><li>Stateful conversations (memory)</li><li>Agent-based reasoning</li></ul><h3>Why is it important?</h3><p>Raw LLMs are:</p><ul><li>Stateless</li><li>Isolated (no tools)</li><li>Limited to prompt context</li></ul><p>LangChain provides:</p><ul><li>Orchestration layer</li><li>Retrieval (RAG)</li><li>Tool usage</li><li>Multi-step reasoning</li></ul><h3>2. Core Components of LangChain</h3><h3>2.1 LLMs and Chat Models</h3><pre>from langchain_openai import ChatOpenAI<br><br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0.7)<br><br>response = llm.invoke(&quot;Explain LangChain.&quot;)<br>print(response.content)</pre><h3>2.2 Prompt Templates</h3><pre>from langchain.prompts import PromptTemplate<br><br>template = PromptTemplate.from_template(<br>    &quot;Explain {topic} in {style} style.&quot;<br>)<br><br>prompt = template.invoke({<br>    &quot;topic&quot;: &quot;LangChain&quot;,<br>    &quot;style&quot;: &quot;simple&quot;<br>})<br><br>print(prompt)</pre><h3>2.3 Chains</h3><pre>from langchain_core.runnables import RunnableSequence<br>from langchain_core.output_parsers import StrOutputParser<br><br>chain = RunnableSequence(template, llm, StrOutputParser())<br><br>print(chain.invoke({<br>    &quot;topic&quot;: &quot;LangChain&quot;,<br>    &quot;style&quot;: &quot;technical&quot;<br>})</pre><h3>2.4 Memory</h3><pre>from langchain.memory import ConversationBufferMemory<br>from langchain.chains import ConversationChain<br><br>memory = ConversationBufferMemory()<br><br>conversation = ConversationChain(llm=llm, memory=memory)<br><br>print(conversation.predict(input=&quot;My name is Nandi&quot;))<br>print(conversation.predict(input=&quot;What is my name?&quot;))</pre><h3>2.5 Agents + Tools</h3><pre>from langchain.agents import initialize_agent<br>from langchain.tools import tool<br><br>@tool<br>def multiply(a: int, b: int) -&gt; int:<br>    return a * b<br><br>agent = initialize_agent(<br>    tools=[multiply],<br>    llm=llm,<br>    agent=&quot;zero-shot-react-description&quot;,<br>    verbose=True<br>)<br><br>agent.invoke(&quot;What is 5 × 6?&quot;)</pre><h3>2.6 Document Loaders</h3><pre>from langchain_community.document_loaders import TextLoader<br><br>loader = TextLoader(&quot;data.txt&quot;)<br>docs = loader.load()</pre><h3>2.7 Vector Stores</h3><pre>from langchain_community.vectorstores import FAISS<br>from langchain_openai import OpenAIEmbeddings<br><br>embeddings = OpenAIEmbeddings()<br>db = FAISS.from_documents(docs, embeddings)</pre><h3>3. Real-World Use Cases</h3><h3>1. Research Assistant</h3><ul><li>Reads PDFs</li><li>Refines queries</li></ul><h3>2. Legal AI</h3><ul><li>Case retrieval</li><li>Iterative validation</li></ul><h3>3. Enterprise Knowledge Bot</h3><ul><li>Multi-source retrieval</li><li>Tool usage</li></ul><h3>4. Advantages and Limitations</h3><h3>Advantages</h3><ul><li>Modular</li><li>Extensible</li><li>Production-ready</li></ul><h3>Limitations</h3><ul><li>Latency</li><li>Cost</li><li>Debug complexity</li></ul><h3>When NOT to use</h3><ul><li>Simple tasks</li><li>Low latency apps</li></ul><h3>5. Code</h3><pre>!pip install -q langchain langchain-core langchain-groq<br>from langchain_core.prompts import PromptTemplate, ChatPromptTemplate<br>import os<br>os.environ[&quot;GROQ_API_KEY&quot;] = &quot;&quot;<br>from langchain_groq import ChatGroq<br>model = ChatGroq(<br>    model=&quot;llama-3.3-70b-versatile&quot;,<br>    temperature=0<br>)</pre><pre>explain_template = PromptTemplate(<br>    input_variables=[&quot;topic&quot;],<br>    template=&quot;Explain {topic} in simple terms for beginners&quot;<br>)<br><br>chain1 = explain_template | model<br><br>response = chain1.invoke({&quot;topic&quot;: &quot;Neural Networks&quot;})<br>print(response.content)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QpPi3xQfyxitstL13HZxQ.png" /></figure><pre>multi_input_template = PromptTemplate(<br>    input_variables=[&quot;topic&quot;, &quot;audience&quot;, &quot;tone&quot;],<br>    template=&quot;Explain {topic} for {audience} in a {tone} tone&quot;<br>)<br><br>chain2 = multi_input_template | model<br><br>test_cases = [<br>    {&quot;topic&quot;: &quot;AI&quot;, &quot;audience&quot;: &quot;beginners&quot;, &quot;tone&quot;: &quot;friendly&quot;},<br>    {&quot;topic&quot;: &quot;Python&quot;, &quot;audience&quot;: &quot;kids&quot;, &quot;tone&quot;: &quot;fun&quot;},<br>    {&quot;topic&quot;: &quot;Deep Learning&quot;, &quot;audience&quot;: &quot;engineers&quot;, &quot;tone&quot;: &quot;technical&quot;}<br>]<br><br>for case in test_cases:<br>    print(f&quot;\nInput: {case}&quot;)<br>    response = chain2.invoke(case)<br>    print(response.content)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_eH9JnBciV187gPAM36BSg.png" /></figure><pre>teaching_template = PromptTemplate(<br>    input_variables=[&quot;topic&quot;],<br>    template=&quot;Explain {topic} clearly step by step&quot;<br>)<br><br>interview_template = PromptTemplate(<br>    input_variables=[&quot;topic&quot;],<br>    template=&quot;Ask 3 interview questions about {topic}&quot;<br>)<br><br>storytelling_template = PromptTemplate(<br>    input_variables=[&quot;topic&quot;],<br>    template=&quot;Explain {topic} as a story&quot;<br>)<br><br>topic = &quot;Machine Learning&quot;<br><br>for name, template in {<br>    &quot;Teaching&quot;: teaching_template,<br>    &quot;Interview&quot;: interview_template,<br>    &quot;Storytelling&quot;: storytelling_template<br>}.items():<br>    chain = template | model<br>    response = chain.invoke({&quot;topic&quot;: topic})<br>    print(f&quot;\n{name} Output:\n&quot;)<br>    print(response.content)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oXL4IB-twMWV9aniMIRNxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2MOV743fm8Z3Z49P75HrQ.png" /></figure><pre>role_map = {<br>    &quot;teacher&quot;: &quot;You are a helpful teacher who explains step by step.&quot;,<br>    &quot;interviewer&quot;: &quot;You are an interviewer who asks sharp and relevant questions.&quot;,<br>    &quot;motivator&quot;: &quot;You are a motivating coach who explains ideas with encouragement.&quot;<br>}<br><br>chat_template = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;{system_role}&quot;),<br>    (&quot;user&quot;, &quot;Explain {topic}&quot;)<br>])<br><br>role = &quot;teacher&quot;<br>topic = &quot;Neural Networks&quot;<br><br>chat_chain = chat_template | model<br><br>response = chat_chain.invoke({<br>    &quot;system_role&quot;: role_map[role],<br>    &quot;topic&quot;: topic<br>})<br><br>print(response.content)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OiOZsgdwn0TAUoXzwmI4aA.png" /></figure><pre>def validate_inputs(audience, tone):<br>    valid_audiences = [&quot;beginner&quot;, &quot;intermediate&quot;, &quot;expert&quot;]<br>    valid_tones = [&quot;formal&quot;, &quot;casual&quot;, &quot;fun&quot;]<br><br>    if audience not in valid_audiences:<br>        audience = &quot;beginner&quot;<br><br>    if tone not in valid_tones:<br>        tone = &quot;formal&quot;<br><br>    return audience, tone<br>style_templates = {<br>    &quot;teaching&quot;: PromptTemplate(<br>        input_variables=[&quot;topic&quot;, &quot;audience&quot;, &quot;tone&quot;],<br>        template=&quot;Explain {topic} for {audience} in a {tone} teaching style&quot;<br>    ),<br>    &quot;interview&quot;: PromptTemplate(<br>        input_variables=[&quot;topic&quot;, &quot;audience&quot;, &quot;tone&quot;],<br>        template=&quot;Ask 3 interview questions about {topic} for {audience} in a {tone} style&quot;<br>    ),<br>    &quot;storytelling&quot;: PromptTemplate(<br>        input_variables=[&quot;topic&quot;, &quot;audience&quot;, &quot;tone&quot;],<br>        template=&quot;Explain {topic} for {audience} in a {tone} storytelling style&quot;<br>    )<br>}<br><br>def generate_prompt(topic, audience, tone, style):<br>    audience, tone = validate_inputs(audience, tone)<br><br>    if style not in style_templates:<br>        raise ValueError(&quot;Style must be one of: teaching, interview, storytelling&quot;)<br><br>    selected_template = style_templates[style]<br>    chain = selected_template | model<br>    response = chain.invoke({<br>        &quot;topic&quot;: topic,<br>        &quot;audience&quot;: audience,<br>        &quot;tone&quot;: tone<br>    })<br>    return response.content<br><br>print(generate_prompt(&quot;Neural Networks&quot;, &quot;beginner&quot;, &quot;fun&quot;, &quot;storytelling&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hieGe73SHfgBDqD6Bj579g.png" /></figure><pre>one_template = PromptTemplate(<br>    input_variables=[&quot;topic&quot;, &quot;audience&quot;, &quot;tone&quot;],<br>    template=&quot;Explain {topic} for {audience} in a {tone} tone&quot;<br>)<br><br>reuse_chain = one_template | model<br><br>inputs = [<br>    {&quot;topic&quot;: &quot;AI&quot;, &quot;audience&quot;: &quot;beginner&quot;, &quot;tone&quot;: &quot;formal&quot;},<br>    {&quot;topic&quot;: &quot;Python&quot;, &quot;audience&quot;: &quot;intermediate&quot;, &quot;tone&quot;: &quot;casual&quot;},<br>    {&quot;topic&quot;: &quot;Deep Learning&quot;, &quot;audience&quot;: &quot;expert&quot;, &quot;tone&quot;: &quot;formal&quot;},<br>    {&quot;topic&quot;: &quot;Data Science&quot;, &quot;audience&quot;: &quot;beginner&quot;, &quot;tone&quot;: &quot;fun&quot;},<br>    {&quot;topic&quot;: &quot;NLP&quot;, &quot;audience&quot;: &quot;expert&quot;, &quot;tone&quot;: &quot;casual&quot;}<br>]<br><br>for item in inputs:<br>    print(f&quot;\nInput: {item}&quot;)<br>    response = reuse_chain.invoke(item)<br>    print(response.content)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpTj5sjSxed-3Bx6F-V_6A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f64f985e169" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POS Tagging vs Chunking: Understanding NLP’s Foundational Layers]]></title>
            <link>https://medium.com/@ark4nandi/pos-tagging-vs-chunking-understanding-nlps-foundational-layers-6cf7abc3019f?source=rss-2ecdb1cc6e98------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cf7abc3019f</guid>
            <category><![CDATA[chunking]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[pos-tagging]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[parts-of-speech]]></category>
            <dc:creator><![CDATA[Dipayan Nandi]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 16:26:57 GMT</pubDate>
            <atom:updated>2026-04-06T16:26:57.931Z</atom:updated>
            <content:encoded><![CDATA[<p>POS tagging and chunking are core NLP techniques that transform raw text into structured data for analysis. While POS tagging labels individual words, chunking groups them into phrases — each building on the other but facing unique hurdles like ambiguity and error propagation.</p><h3>Core Differences</h3><p>POS tagging assigns grammatical categories like noun (NN), verb (VB), or adjective (JJ) to each word based on context. Chunking, or shallow parsing, takes those tags and identifies multi-word phrases like noun phrases (NP) or verb groups without full sentence syntax trees.</p><p>POS tagging operates word-by-word, making it foundational but limited to single-token labels. Chunking builds hierarchical structures, grouping contiguous tagged words (e.g., “the quick brown fox” as one NP chunk) for tasks like named entity recognition.</p><h3>Key Challenges</h3><p>Ambiguity plagues POS tagging: “bass” could be a fish (NN) or low sound (JJ), resolved via context but often wrong in rare cases. Chunking inherits these errors — wrong tags lead to failed phrase detection, causing error propagation downstream.</p><p>Chunking adds pattern complexity; rules like {&lt;DT&gt;?&lt;JJ&gt;*&lt;NN&gt;} must balance coverage and precision. Deep learning mitigates some issues but amplifies propagation in pipelines.</p><h3>NLTK Implementation</h3><p>NLTK’s pos_tag uses the averaged perceptron tagger on tokenized text from corpora like state_union. Chunking follows with RegexpParser defining grammar rules on tagged output.</p><pre>import nltk<br>from nltk.corpus import state_union<br>from nltk import pos_tag, word_tokenize, RegexpParser<br><br>nltk.download(&#39;punkt_tab&#39;)<br>nltk.download(&#39;state_union&#39;)<br>nltk.download(&#39;averaged_perceptron_tagger&#39;)<br><br>text = state_union.raw(&quot;2006-GWBush.txt&quot;)[:500]<br>tokens = word_tokenize(text)<br>tagged = pos_tag(tokens)<br><br>print(&quot;POS Tagging Output (first 20 tokens):&quot;)<br>for word, tag in tagged[:20]:<br>    print(f&quot;{word}: {tag}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*myI6RvuI9SLTMNnoFYk3QA.png" /><figcaption>output1</figcaption></figure><pre>import nltk<br>from nltk.corpus import state_union<br>from nltk import pos_tag, word_tokenize, RegexpParser<br>chunk_grammar = r&quot;&quot;&quot;<br>    NP: {&lt;DT|JJ|NN.*&gt;*&lt;NN.*&gt;+}  # Noun Phrase<br>    VP: {&lt;VB.*&gt;+}              # Verb Phrase<br>&quot;&quot;&quot;<br>chunk_parser = RegexpParser(chunk_grammar)<br><br>text = state_union.raw(&quot;2006-GWBush.txt&quot;)[:500]<br>tokens = word_tokenize(text)<br>tagged = pos_tag(tokens)<br>chunked = chunk_parser.parse(tagged[:50])<br><br>print(&quot;📊 CHUNKING TREE (Text Format):&quot;)<br>print(chunked.pretty_print())<br><br>print(&quot;\n🎯 EXTRACTED NOUN PHRASES:&quot;)<br>for subtree in chunked.subtrees(filter=lambda t: t.label() == &#39;NP&#39;):<br>    phrase = &#39; &#39;.join(word for word, tag in subtree.leaves())<br>    print(f&quot;NP: &#39;{phrase}&#39; → {subtree}&quot;)<br><br>print(&quot;\n🎯 EXTRACTED VERB PHRASES:&quot;)<br>for subtree in chunked.subtrees(filter=lambda t: t.label() == &#39;VP&#39;):<br>    phrase = &#39; &#39;.join(word for word, tag in subtree.leaves())<br>    print(f&quot;VP: &#39;{phrase}&#39; → {subtree}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6-U0OfCijuafS81tDvW8Q.png" /><figcaption>output2</figcaption></figure><p>These snippets show tagging’s flat labels vs. chunking’s tree structure on real US State of the Union data.</p><h3>Deep Learning Insights</h3><p>Traditional NLTK taggers hit ~97% word accuracy on Penn Treebank but drop on ambiguous text. Deep learning models like BiLSTMs or Transformers (BERT fine-tuned) reach 98%+ F1, handling context better via embeddings.</p><p>Chunking accuracies follow: rule-based ~85–90% NP F1, neural chunkers ~92–95%. Error propagation shrinks the gap — chunking forgives some tag errors if patterns match. Recent models integrate joint tagging/chunking to cut propagation.</p><h3>Practical Takeaways</h3><p>Use POS tagging for lexicon analysis, chunking for phrase extraction in NER or summarization. Pipeline them carefully: preprocess consistently (e.g., lowercasing breaks proper nouns).</p><p>Deep learning outperforms on diverse text, but NLTK rules shine for quick prototyping.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cf7abc3019f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Raw Text to Model-Ready Data: Building an NLP Pipeline Step-by-Step]]></title>
            <link>https://medium.com/@ark4nandi/from-raw-text-to-model-ready-data-building-an-nlp-pipeline-step-by-step-a90342c15862?source=rss-2ecdb1cc6e98------2</link>
            <guid isPermaLink="false">https://medium.com/p/a90342c15862</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Dipayan Nandi]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 03:47:30 GMT</pubDate>
            <atom:updated>2026-03-31T03:47:30.825Z</atom:updated>
            <content:encoded><![CDATA[<p>Natural Language Processing (NLP) powers the AI we interact with daily, turning messy human language into structured info that machines can learn from. In this blog, we’ll walk through a complete NLP pipeline, starting from raw text and ending with inputs ready for machine learning models. Whether you’re building a chatbot or analyzing customer reviews, understanding this pipeline is key.</p><h3>1. Introduction to NLP: What It Is and Why Preprocessing Matters</h3><h3>What is NLP?</h3><p>NLP is a branch of AI that helps computers understand, interpret, and generate human language. It bridges the gap between unstructured text like emails, tweets, or articles and the numerical data models need.</p><h3>Why Preprocessing is Required</h3><p>Raw text is chaotic: wrong capitalization, punctuation, and noise make it hard for models to spot patterns. Preprocessing cleans it, reducing noise, cutting computation costs, and boosting model accuracy. Without it, a model might treat “Apple” (fruit) and “apple” (company) as identical, leading to errors.</p><h3>Real-World Examples</h3><ul><li><strong>Chatbots</strong>: Preprocess user queries to extract intent, like turning “Where’s my order???” into clean tokens for response generation.</li><li><strong>Sentiment Analysis</strong>: Clean reviews to detect positivity in “Loved it! 😍” despite emojis.</li><li><strong>Search Engines</strong>: Vectorize queries and documents for relevance matching, powering Google-like results.</li></ul><h3>2. Text Preprocessing Steps: The Core Cleanup</h3><p>Sample sentence: “Running quickly! The dogs are playing??”</p><h3>Converting to lowercase</h3><p><strong>Definition</strong>: Convert all text to lowercase.<br><strong>Importance</strong>: Ensures “Run” and “run” are treated the same, reducing vocabulary size by up to 30%.<br><strong>Example</strong>: “Running quickly! The dogs are playing??” -&gt;“running quickly! the dogs are playing??”</p><h3>Removal of Punctuation</h3><p><strong>Definition</strong>: Strip out symbols like !, ?, ., commas.<br><strong>Importance</strong>: Punctuation adds noise.<br><strong>Example</strong>: “running quickly! the dogs are playing??” -&gt;“running quickly the dogs are playing”</p><h3>Removal of Stopwords</h3><p><strong>Definition</strong>: Eliminate common words like “the,” “are,” “is” (from lists like NLTK’s English stopwords).<br><strong>Importance</strong>: Stopwords make up 40–60% of text but carry little meaning sp removing them highlights key terms.<br><strong>Example</strong>: “running quickly the dogs are playing” -&gt;“running quickly dogs playing”</p><h3>Tokenization</h3><p><strong>Definition</strong>: Split text into words or subwords (tokens).<br><strong>Importance</strong>: Breaks text into model-digestible units; essential for counting or embedding.<br><strong>Example</strong>: “running quickly dogs playing” -&gt;[“running”, “quickly”, “dogs”, “playing”]</p><h3>Stemming</h3><p><strong>Definition</strong>: Chop words to their root form (e.g., Porter Stemmer removes suffixes).<br><strong>Importance</strong>: Normalizes variations like “running” → “run,” shrinking vocabulary.<br><strong>Example</strong>: [“running”, “quickly”, “dogs”, “playing”] -&gt;[“run”, “quickli”, “dog”, “play”] (Note: Can be crude, creating fake words like “quickli”.)</p><h3>Lemmatization</h3><p><strong>Definition</strong>: Reduce words to their dictionary base form (e.g., using WordNet), considering context.<br><strong>Importance</strong>: More accurate than stemming; preserves meaning (e.g., “better” → “good”).<br><strong>Example</strong>: [“running”, “quickly”, “dogs”, “playing”] -&gt;[“run”, “quickly”, “dog”, “play”]</p><h3>3. Text Cleaning Challenges: Tackling Real-World Mess</h3><p>Raw data from social media or web scrapes is noisy. Here’s how to handle it:</p><h3>Handling Emojis</h3><p>Emojis convey emotion but aren’t text. Convert to descriptions (e.g., 😍 → “heart_eyes”) or remove them. Importance: Retains sentiment in tweets like “Great product! 🔥” → “great product fire”.</p><h3>Handling URLs and Special Characters</h3><p>Strip URLs (e.g., <a href="https://example.com/">https://example.com</a> → “”) and extras like @mentions or #hashtags. Importance: Prevents models from learning irrelevant patterns from links.</p><h3>Dealing with Noisy Text (Social Media Data)</h3><p>Social posts have abbreviations (lol → laugh out loud), typos, or multilingual mixes. Use regex for normalization. Example: “Gr8 job!! luv it 💕” → “great job love it”. Tools like spaCy or NLTK automate much of this.</p><h3>4. Feature Engineering (Vectorization): Turning Text into Numbers</h3><p>Preprocessing yields clean tokens; vectorization converts them to numerical vectors for models like neural networks.</p><h3>Bag of Words (BoW)</h3><p><strong>Intuition</strong>: Treat text as a “bag” of words, ignoring order.<br><strong>Working</strong>: Create a vocabulary; count occurrences (e.g., vocab: [“run”, “dog”] → for “run dog dog”).<br><strong>Advantages</strong>: Simple, fast. <strong>Limitations</strong>: Ignores order/semantics; high-dimensional/sparse.</p><h3>TF-IDF (Term Frequency-Inverse Document Frequency)</h3><p><strong>Intuition</strong>: Weigh words by importance across a corpus.<br><strong>Working</strong>: TF = word count in doc; IDF = log(total docs / docs with word); TF-IDF = TF × IDF. Rare words score higher. Example: “dog” in pet reviews gets high TF-IDF.<br><strong>Advantages</strong>: Handles varying lengths, downweights commons. <strong>Limitations</strong>: Still bag-of-words, no context.</p><h3>Word2Vec</h3><p><strong>Intuition</strong>: Words in similar contexts have similar vectors (e.g., king — man + woman ≈ queen).<br><strong>Working</strong>: Train on corpus using Skip-gram/CBOW to predict neighbors; yields dense 300D vectors per word. Average for document vectors.<br><strong>Advantages</strong>: Captures semantics. <strong>Limitations</strong>: Needs large data; static (no polysemy).</p><h3>Average Word2Vec</h3><p><strong>Intuition</strong>: Average pre-trained Word2Vec vectors of a document’s words.<br><strong>Working</strong>: For “dogs run,” avg(vec(“dogs”) + vec(“run”)).<br><strong>Advantages</strong>: Simple doc representation. <strong>Limitations</strong>: Loses word order; sensitive to rare words.</p><pre>| Technique        | Context Awareness            | Sparsity            | Performance                                  |<br>|------------------|------------------------------|---------------------|----------------------------------------------|<br>| **BoW**          | None (order-blind)           | High (mostly zeros) | Fast but poor on semantics                   |<br>| **TF-IDF**       | None                         | High                | Better than BoW for rarity; great for search |<br>| **Word2Vec**     | High (semantic similarity)   | Low (dense)         | Excels in analogies; compute-heavy           |<br>| **Avg Word2Vec** | Medium (doc-level semantics) | Low                 | Quick for classification; loses sequence     |</pre><h3>A Demonstration</h3><pre>import re<br>import string<br>import numpy as np<br>import pandas as pd<br>import nltk<br>from nltk.tokenize import word_tokenize<br>from nltk.corpus import stopwords<br>from nltk.stem import PorterStemmer, WordNetLemmatizer<br>from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer<br>from gensim.models import Word2Vec<br>nltk.download(&quot;punkt&quot;)<br>nltk.download(&quot;stopwords&quot;)<br>nltk.download(&quot;wordnet&quot;)<br>nltk.download(&quot;omw-1.4&quot;)<br>documents = [<br>    &quot;I absolutely loved this movie!!! 😍 The acting was amazing and the story was touching.&quot;,<br>    &quot;Terrible product... waste of money :( Visit https://example.com for details.&quot;,<br>    &quot;The chatbot answered my question quickly, but the reply felt robotic.&quot;,<br>    &quot;Search engines process billions of queries every day!!!&quot;,<br>    &quot;Dogs are running faster than the other animals in the park.&quot;,<br>    &quot;LOL this phone is gr8!!! Battery life is awesome 🔥 #happy&quot;<br>]<br>stop_words = set(stopwords.words(&quot;english&quot;))<br>stemmer = PorterStemmer()<br>lemmatizer = WordNetLemmatizer()<br>def remove_urls(text):<br>    return re.sub(r&quot;http\S+|www\S+&quot;, &quot;&quot;, text)<br>def remove_emojis(text):<br>    emoji_pattern = re.compile(<br>        &quot;[&quot;<br>        &quot;\U0001F600-\U0001F64F&quot;<br>        &quot;\U0001F300-\U0001F5FF&quot;<br>        &quot;\U0001F680-\U0001F6FF&quot;<br>        &quot;\U0001F1E0-\U0001F1FF&quot;<br>        &quot;\U00002700-\U000027BF&quot;<br>        &quot;\U000024C2-\U0001F251&quot;<br>        &quot;]+&quot;,<br>        flags=re.UNICODE,<br>    )<br>    return emoji_pattern.sub(&quot;&quot;, text)<br>def remove_special_characters(text):<br>    return re.sub(r&quot;[^a-zA-Z0-9\s]&quot;, &quot;&quot;, text)<br>def lowercase(text):<br>    return text.lower()<br>def remove_punctuation(text):<br>    return text.translate(str.maketrans(&quot;&quot;, &quot;&quot;, string.punctuation))<br>def preprocess_text(text, show_steps=False):<br>    steps = {}<br>    steps[&quot;raw&quot;] = text<br>    text = remove_urls(text)<br>    steps[&quot;remove_urls&quot;] = text<br>    text = remove_emojis(text)<br>    steps[&quot;remove_emojis&quot;] = text<br>    text = lowercase(text)<br>    steps[&quot;lowercase&quot;] = text<br>    text = remove_punctuation(text)<br>    steps[&quot;remove_punctuation&quot;] = text<br>    text = remove_special_characters(text)<br>    steps[&quot;remove_special_characters&quot;] = text<br>    tokens = word_tokenize(text)<br>    steps[&quot;tokenization&quot;] = tokens<br>    tokens_no_stop = [word for word in tokens if word not in stop_words]<br>    steps[&quot;remove_stopwords&quot;] = tokens_no_stop<br>    stemmed_tokens = [stemmer.stem(word) for word in tokens_no_stop]<br>    steps[&quot;stemming&quot;] = stemmed_tokens<br>    lemmatized_tokens = [lemmatizer.lemmatize(word) for word in tokens_no_stop]<br>    steps[&quot;lemmatization&quot;] = lemmatized_tokens<br>    if show_steps:<br>        return steps<br>    return {<br>        &quot;clean_text&quot;: &quot; &quot;.join(lemmatized_tokens),<br>        &quot;tokens&quot;: tokens,<br>        &quot;tokens_no_stop&quot;: tokens_no_stop,<br>        &quot;stemmed_tokens&quot;: stemmed_tokens,<br>        &quot;lemmatized_tokens&quot;: lemmatized_tokens<br>    }<br>sample = documents[0]<br>demo_steps = preprocess_text(sample, show_steps=True)<br>print(&quot;\n===PIPELINE===\n&quot;)<br>for step, value in demo_steps.items():<br>    print(f&quot;{step.upper()}:&quot;)<br>    print(value)<br>    print()<br>processed_docs = []<br>tokenized_docs = []<br>for doc in documents:<br>    result = preprocess_text(doc)<br>    processed_docs.append(result[&quot;clean_text&quot;])<br>    tokenized_docs.append(result[&quot;lemmatized_tokens&quot;])<br>print(&quot;\n=== CLEANED DOCUMENTS ===\n&quot;)<br>for i, doc in enumerate(processed_docs, 1):<br>    print(f&quot;Doc {i}: {doc}&quot;)<br>print(&quot;\n=== BAG OF WORDS (BoW) ===\n&quot;)<br>bow_vectorizer = CountVectorizer()<br>bow_matrix = bow_vectorizer.fit_transform(processed_docs)<br>bow_df = pd.DataFrame(<br>    bow_matrix.toarray(),<br>    columns=bow_vectorizer.get_feature_names_out()<br>)<br>print(&quot;Vocabulary:&quot;)<br>print(bow_vectorizer.get_feature_names_out())<br>print(&quot;\nBoW Matrix:&quot;)<br>print(bow_df)<br>print(&quot;\n=== TF-IDF ===\n&quot;)<br>tfidf_vectorizer = TfidfVectorizer()<br>tfidf_matrix = tfidf_vectorizer.fit_transform(processed_docs)<br>tfidf_df = pd.DataFrame(<br>    tfidf_matrix.toarray(),<br>    columns=tfidf_vectorizer.get_feature_names_out()<br>)<br>print(&quot;Vocabulary:&quot;)<br>print(tfidf_vectorizer.get_feature_names_out())<br>print(&quot;\nTF-IDF Matrix:&quot;)<br>print(tfidf_df.round(3))<br>print(&quot;\n=== WORD2VEC ===\n&quot;)<br>w2v_model = Word2Vec(<br>    sentences=tokenized_docs,<br>    vector_size=20,<br>    window=3,<br>    min_count=1,<br>    workers=1,<br>    sg=0<br>)<br>word = &quot;movie&quot;<br>if word in w2v_model.wv:<br>    print(f&quot;Vector for &#39;{word}&#39;:&quot;)<br>    print(w2v_model.wv[word])<br><br>    print(f&quot;\nMost similar words to &#39;{word}&#39;:&quot;)<br>    print(w2v_model.wv.most_similar(word, topn=5))<br>else:<br>    print(f&quot;&#39;{word}&#39; not found in vocabulary.&quot;)<br>print(&quot;\n=== AVERAGE WORD2VEC ===\n&quot;)<br>def average_word2vec(tokens, model, vector_size):<br>    valid_vectors = [model.wv[word] for word in tokens if word in model.wv]<br>    if len(valid_vectors) == 0:<br>        return np.zeros(vector_size)<br>    return np.mean(valid_vectors, axis=0)<br>avg_vectors = np.array([<br>    average_word2vec(tokens, w2v_model, 20) for tokens in tokenized_docs<br>])<br>avg_w2v_df = pd.DataFrame(avg_vectors)<br>print(&quot;Average Word2Vec document vectors:&quot;)<br>print(avg_w2v_df.round(3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5OSYs8OmfW8trWxHwbViQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*V14G29DzWT9ght0IhYp0Yg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*hjzvi08IwhF6kJ41qZopvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*io3sgujd6U-P_auY7MwoPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WuYKNfJgtPILuU0K4bf8uA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a90342c15862" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lists vs Tuples in Python: When Should You Use Which?]]></title>
            <link>https://medium.com/@ark4nandi/lists-vs-tuples-in-python-when-should-you-use-which-018ec3913ed4?source=rss-2ecdb1cc6e98------2</link>
            <guid isPermaLink="false">https://medium.com/p/018ec3913ed4</guid>
            <category><![CDATA[lists-vs-tuples-in-python]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Dipayan Nandi]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 05:59:59 GMT</pubDate>
            <atom:updated>2026-02-16T06:01:00.705Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there, Python newbie! If you’ve been coding in Python for a bit, you’ve probably leaned hard on <strong>lists</strong> — those handy square-bracketed collections like [1, 2, 3]. They&#39;re everywhere in beginner tutorials. But then you stumble upon <strong>tuples</strong>, those round-bracketed cousins like (1, 2, 3), and wonder: <em>What&#39;s the difference? Do I even need them?</em></p><p>The short answer? Lists and tuples both store ordered collections of items, but they shine in different scenarios. Lists are flexible and changeable (mutable), perfect for data that evolves. Tuples are fixed and unchangeable (immutable), ideal for data that shouldn’t shift — like coordinates or constants. Choosing wrong can waste memory, slow your code, or even cause bugs.</p><p>In this post, we’ll unpack mutability, performance, memory usage, and real-world use cases. By the end, you’ll know exactly when to grab lists or tuples. Let’s dive in — no PhD required!</p><h3>What Are Lists and Tuples? A Quick Breakdown</h3><p>Python data structures are like toolbox items: pick the right one for the job.</p><ul><li><strong>Lists</strong> ([]): Ordered, mutable sequences. Add, remove, or change items anytime. Great for dynamic data.</li><li><strong>Tuples</strong> (()): Ordered, immutable sequences. Once created, they&#39;re locked. Use for fixed data.</li></ul><p>Both support indexing (e.g., my_list[0] grabs the first item) and slicing (e.g., my_list[1:3] for a subset). But mutability is the game-changer.</p><p><strong>Mutability in Action</strong><br> Lists let you tweak contents post-creation. Tuples say “nope” with an error.</p><pre>shopping_list = [&#39;apples&#39;, &#39;bananas&#39;, &#39;oranges&#39;]<br>shopping_list[1] = &#39;grapes&#39;  # Easy change!<br>print(shopping_list)  # Output: [&#39;apples&#39;, &#39;grapes&#39;, &#39;oranges&#39;]<br><br>coords = (10, 20, 30)<br>coords[1] = 25  # Boom! TypeError: &#39;tuple&#39; object does not support item assignment<br>print(coords)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*JlMnGW2kCWs54HdingrJ4g.png" /></figure><p><strong>Output Explanation</strong>: The list updates smoothly, reflecting real-life flexibility (like editing a to-do list). The tuple throws a TypeError, enforcing data integrity—perfect for values that must stay constant, like a planet&#39;s fixed orbital parameters.</p><p>Why care? Mutability affects everything downstream: performance, memory, and safety.</p><h3>Memory Usage: Tuples Win the Efficiency Race</h3><p>Lists guzzle more memory because Python allocates extra space for potential changes (over-allocation). Tuples are compact since they’re immutable — no resize buffer needed.</p><p>Let’s measure with sys.getsizeof():</p><pre>import sys<br>my_list = [1, 2, 3, 4, 5]<br>my_tuple = (1, 2, 3, 4, 5)</pre><pre>print(f&quot;List memory: {sys.getsizeof(my_list)} bytes&quot;)<br>print(f&quot;Tuple memory: {sys.getsizeof(my_tuple)} bytes&quot;)</pre><p><strong>Output Explanation</strong>: On most systems, the tuple uses ~30–40% less memory for the same data. Scale this to millions of items (think big datasets), and lists could double your RAM needs. Tuples are lean machines!</p><p>Pro tip: Tuples also cache small integers, shaving off even more overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*dcT6ICuxFp0GIcwC5rPzng.png" /></figure><h3>Performance: Speed Demons Compared</h3><p>Tuples edge out lists in speed for reads and iterations — common ops in data processing. Lists shine for writes, but if you’re mostly reading, tuples iterate faster due to no mutability checks.</p><p>Benchmark it yourself:</p><pre>import timeit<br>setup_list = &quot;data_list = list(range(1000))&quot;<br>stmt_list = &quot;sum(data_list)&quot;<br>list_time = timeit.timeit(stmt=stmt_list, setup=setup_list, number=10000)<br><br>setup_tuple = &quot;data_tuple = tuple(range(1000))&quot;<br>stmt_tuple = &quot;sum(data_tuple)&quot;<br>tuple_time = timeit.timeit(stmt=stmt_tuple, setup=setup_tuple, number=10000)<br><br>print(f&quot;List sum time: {list_time:.4f}s&quot;)  <br>print(f&quot;Tuple sum time: {tuple_time:.4f}s&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*oU_ZCbcmRNK3LdtEW-2N4A.png" /></figure><p><strong>Output Explanation</strong>: The tuple finishes quicker because Python skips safety checks for modifications. For huge loops or APIs returning fixed data, this adds up — tuples can boost speed by 20–50%.</p><p>Lists pull ahead for appends/pops, though. Test data_list.append(1000) vs trying it on a tuple (impossible!).</p><h3>Real-World Use Cases: Shopping Cart vs GPS Coordinates</h3><h3>Use Lists: Dynamic, Growing Data</h3><p>Imagine a <strong>shopping cart app</strong>. Items change — add milk, remove expired yogurt.</p><pre>cart = []<br>cart.append(&#39;apples&#39;)<br>cart.extend([&#39;bread&#39;, &#39;milk&#39;])<br>cart.remove(&#39;bread&#39;)<br>print(cart)<br>print(len(cart))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*ix0iW1TDY5jpysbORojOcg.png" /></figure><p>This mutability handles user edits seamlessly.</p><h3>Use Tuples: Fixed, Reliable Data</h3><p>Now picture a <strong>GPS navigation system</strong>. Coordinates like latitude/longitude must never change mid-route — altering them could crash your car (metaphorically)!</p><pre>home = (40.7128, -74.0060)<br>current_pos = (40.7589, -73.9851)<br><br>distance = ((home[0] - current_pos[0])**2 + (home[1] - current_pos[1])**2)**0.5<br>print(f&quot;Distance to home: {distance:.4f} units&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*Ea61kD4nB7rwQTsCDt-B-g.png" /></figure><p><strong>Why Tuple?</strong> Accidental changes (e.g., a bug overwriting lat) are impossible. Bonus: Tuples unpack neatly: lat, lon = home.</p><p><strong>Pro Scenario: API Responses</strong><br> APIs often return tuples for fixed records (e.g., (user_id, name, age)). Lists for editable user carts. In data science, tuples store constants like (pi, gravity); lists hold evolving experiment results.</p><h3>When to Choose Which? Your Decision Cheat Sheet<br>| Scenario | Pick List | Pick Tuple |<br>|-----------------------|--------------------|------------------------|<br>| Data changes often | ✅ Shopping lists | ❌ (Can&#39;t modify) |<br>| Fixed values | ❌ Risky overwrites| ✅ Coordinates, configs|<br>| Heavy reading/loops | ❌ Slower | ✅ Faster iteration |<br>| Memory-critical | ❌ Higher usage | ✅ Compact |<br>| Function returns | ✅ Multiple values | ✅ Single-use returns |</h3><p>Rule of thumb: If data might change, list it up. If it’s set in stone, tuple it.</p><h3>Wrap-Up: Level Up Your Python Choices</h3><p>Lists and tuples aren’t rivals — they’re teammates. Lists flex for mutable mayhem; tuples lock in efficiency and safety. Start defaulting to tuples for small, fixed collections — you’ll notice snappier code and happier memory usage.</p><p>Next time you’re coding, ask: “Will this change?” No? Tuple. Yes? List. Experiment with the snippets above in your IDE.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=018ec3913ed4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>