<?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 Harman Bhatia on Medium]]></title>
        <description><![CDATA[Stories by Harman Bhatia on Medium]]></description>
        <link>https://medium.com/@imharmanbhatia?source=rss-12e4d7a478d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TjWPBAo8BgL0b3n-0rAoDA.jpeg</url>
            <title>Stories by Harman Bhatia on Medium</title>
            <link>https://medium.com/@imharmanbhatia?source=rss-12e4d7a478d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:54:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imharmanbhatia/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[All about AI in Snowflake [2025]]]></title>
            <link>https://imharmanbhatia.medium.com/all-about-ai-in-snowflake-2025-efb8f47f9f28?source=rss-12e4d7a478d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb8f47f9f28</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <dc:creator><![CDATA[Harman Bhatia]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 13:51:30 GMT</pubDate>
            <atom:updated>2025-07-06T13:51:30.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlbgFvpby6XXwOOzRBhTsQ.jpeg" /></figure><p>Snowflake has evolved from just another data warehouse to an AI-powered smart data warehouse. There are a lot of new Generative AI features included in the Snowflake stack that we will go through in this blog.</p><p>Snowflake has acquired around 11 companies to feature its AI ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*jBwvYjjagye8b84ZY5nWqw.png" /></figure><h4>Snowflake Cortex</h4><p>Snowflake Cortex is a comprehensive collection of AI capabilities that leverage large language models (LLMs) to interpret unstructured data, respond to open-ended questions, and offer smart assistance. This collection of AI features from Snowflake includes:</p><ul><li>Snowflake Cortex LLM Functions</li><li>Snowflake Copilot</li><li>Document AI</li><li>Cortex Fine-tuning</li><li>Cortex Search</li><li>Cortex Analyst</li></ul><h4>Snowflake Cortex LLM Functions</h4><p>I used almost all the Snowflake LLM functions to test their working and performance. These functions allow developers and analysts to embed generative AI capabilities directly within SQL. Functions like LLM_COMPLETE, LLM_CHAT, and LLM_SUMMARIZE let users generate text, chat with documents, or summarize content using Snowflake&#39;s hosted models—all without moving data out of Snowflake.</p><p>For instance, I tested LLM_COMPLETE by passing in prompts like <em>&quot;Generate a sales pitch for our product&quot;</em> and was surprised by the contextual understanding it demonstrated, especially with access to domain-specific tables. Similarly, LLM_SUMMARIZE was handy in quickly digesting long marketing reports and customer reviews stored as unstructured text.</p><p>What makes this powerful is the <strong>governance</strong> and <strong>security</strong> of running these AI operations inside the Snowflake platform — your data never leaves your environment.</p><p>Let’s say you want to <strong>summarize customer reviews</strong> stored in a table:</p><pre>SELECT<br>  review_id,<br>  LLM_SUMMARIZE(review_text) AS summary<br>FROM customer_reviews<br>LIMIT 10;</pre><p>Or use LLM_COMPLETE to <strong>generate content</strong> from a prompt:</p><pre>SELECT<br>  LLM_COMPLETE(&#39;Write a cold email for a data analytics product&#39;) AS generated_email;</pre><p>Want to chat with data? Try LLM_CHAT:</p><pre>SELECT<br>  LLM_CHAT(&#39;You are a data analyst. What insights do you get from this dataset: ...&#39;) AS response;</pre><p>You can even pass structured data as JSON and ask questions about it. The functions support both <strong>Snowflake-hosted models</strong> and <strong>bring-your-own-model</strong> (BYOM) options.</p><h4>Snowflake Copilot</h4><p>Copilot is Snowflake’s AI assistant integrated directly into the UI. Think of it as ChatGPT but for your Snowflake workloads. You can ask questions like:</p><ul><li><em>“What is the trend of weekly active users for the past 6 months?”</em></li><li><em>“Can you write a query to join sales with customer demographics?”</em></li></ul><p>The tool auto-generates SQL queries, offers visualizations, and even explains existing queries. For non-SQL experts, Copilot bridges the gap between data intent and data action, dramatically accelerating insight generation.</p><p>Example prompt inside Copilot:</p><blockquote>“Generate a query to show weekly sales grouped by category for the last 3 months.”</blockquote><p>Copilot outputs:</p><pre>SELECT<br>  category,<br>  WEEK(order_date) AS sales_week,<br>  SUM(sales_amount) AS total_sales<br>FROM orders<br>WHERE order_date &gt;= DATEADD(MONTH, -3, CURRENT_DATE())<br>GROUP BY category, WEEK(order_date);</pre><h4>Document AI</h4><p>This is one of the most exciting use cases — especially for businesses handling contracts, invoices, and PDFs. Document AI enables users to extract structured data from unstructured documents using fine-tuned LLMs.</p><p>For example, I uploaded sample invoices in PDF format, and within seconds, Snowflake returned a structured table with vendor_name, invoice_amount, due_date, and more—no custom OCR pipelines or third-party integrations needed.</p><pre>SELECT<br>  document_name,<br>  EXTRACT_TEXT_FROM_DOCUMENT(document_binary) AS raw_text<br>FROM uploaded_documents;</pre><p>You can also combine this with LLM_SUMMARIZE or REGEXP functions to extract key values like invoice_total or due_date. It’s a game-changer for industries like finance, insurance, and logistics.</p><h4>Cortex Fine-Tuning</h4><p>Cortex Fine-Tuning allows you to tailor large language models with your proprietary data — right inside Snowflake. You can fine-tune models for specific use cases like support chatbots, legal text analysis, or domain-specific summarization.</p><pre>CALL CORTEX.FINE_TUNE(<br>  MODEL_NAME =&gt; &#39;cortex/gpt-base&#39;,<br>  TRAINING_DATA =&gt; (<br>    SELECT prompt, response FROM support_chat_logs<br>  ),<br>  PARAMETERS =&gt; {&#39;epochs&#39;: 3, &#39;learning_rate&#39;: 0.001}<br>);</pre><p>Once fine-tuned, use your new model:</p><pre>SELECT<br>  MY_CUSTOM_LLM_COMPLETE(&#39;Generate a response for: My order hasn’t arrived&#39;) AS reply;</pre><p>One of the standout features is how seamlessly Snowflake abstracts the complexity of fine-tuning — no ML engineering required. Just point to your data, define the task, and the system handles the rest.</p><h4>Cortex Search</h4><p>Cortex Search is Snowflake’s semantic search engine powered by vector embeddings. Unlike traditional keyword search, this allows you to search based on <em>meaning</em> rather than exact matches.</p><p>You can embed documents or text fields using VECTORIZE_TEXT() and then use vector similarity to retrieve relevant results. It’s ideal for recommendation systems, Q&amp;A interfaces, or finding similar cases in support tickets.</p><p>Step 1: Create embeddings</p><pre>SELECT<br>  doc_id,<br>  VECTORIZE_TEXT(content) AS embedding<br>FROM knowledge_base;</pre><p>Step 2: Query similar content</p><pre>SELECT<br>  doc_id,<br>  VECTOR_SIMILARITY(<br>    VECTORIZE_TEXT(&#39;how to reset password&#39;),<br>    embedding<br>  ) AS similarity_score<br>FROM knowledge_base<br>ORDER BY similarity_score DESC<br>LIMIT 5;</pre><p>You’re not just searching for keywords — you’re searching <strong>by meaning</strong>.</p><h4>Cortex Analyst (New in 2025)</h4><p>A recent and exciting launch in 2025 is <strong>Cortex Analyst</strong>, a natural language interface over structured and unstructured data. It can ingest data models, metrics, and documentation to provide accurate, contextual answers — perfect for building internal AI-powered data analysts.</p><p>Cortex Analyst can answer questions like:</p><ul><li><em>“What is the average revenue by region this quarter?”</em></li><li><em>“List key reasons for churn mentioned in the last 100 support calls.”</em></li></ul><p>Think of it as a smarter data concierge trained on your business.</p><h3>Bonus: Combine LLM + Streamlit for AI Apps</h3><p>Build end-to-end <strong>AI-powered apps</strong> using <strong>Streamlit in Snowflake</strong>:</p><pre># Inside Snowflake Native App (Streamlit)<br>import streamlit as st<br>import snowflake.connector<br><br>conn = snowflake.connector.connect(...)<br>query = &quot;SELECT LLM_SUMMARIZE(feedback_text) FROM product_feedback LIMIT 10&quot;<br>results = conn.cursor().execute(query).fetchall()<br><br>for summary in results:<br>    st.write(summary[0])</pre><p>Now you can serve LLM outputs directly to your end-users.</p><h3>Final Thoughts</h3><p>Snowflake has redefined what a <strong>data platform</strong> means. With Cortex, Document AI, vector search, and in-database LLMs, it’s never been easier to build intelligent apps, perform AI-powered analytics, and derive value from unstructured data.</p><p>If you’re already working with Snowflake, now is the time to <strong>experiment with Cortex features</strong> and bring GenAI into your workflows.</p><p><strong>Bonus Tip:</strong> Start with LLM_SUMMARIZE on your Slack conversations or Jira tickets. It’s the fastest way to get value from unstructured data.</p><h4>Before You Leave:</h4><p>If you liked this article, please give it a few claps, <strong>follow me</strong> to stay updated on future posts, and share it with your network if you think it could help someone.</p><p>I hope this guide was helpful. If you have any questions or thoughts, feel free to drop them in the comments.</p><p>I also offer <strong>consultancy services</strong> in areas such as:</p><ul><li>Data warehouse migrations</li><li>Cost optimization in cloud data platforms</li><li>Data governance and management strategies</li><li>Data modelling for modern analytics</li><li>AI Automation in Data Engineering</li></ul><p>If you need support in any of these areas, I’d be glad to help.</p><p>📧 Email: imharmanbhatia@gmail.com<br> 💼 Connect on <a href="https://www.linkedin.com/in/imharmanbhatia/">LinkedIn</a></p><p>Let’s build smarter data systems — together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb8f47f9f28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Migration Made Easy with Snowflake Hybrid Tables]]></title>
            <link>https://towardsdev.com/data-migration-made-easy-with-snowflake-hybrid-tables-849cdbbb51d7?source=rss-12e4d7a478d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/849cdbbb51d7</guid>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-migration]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Harman Bhatia]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 09:15:25 GMT</pubDate>
            <atom:updated>2024-04-15T16:51:43.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcErC4oEns2wfwt1llkN0w.png" /></figure><p>Multiple issues arise while migrating from traditional databases (such as Oracle, and SQL Server) to Snowflake due to the lack of basic database and table-level features i.e. Primary Keys, Foreign Keys and Indexes.</p><ol><li>Referential Integrity: In Snowflake, the foreign keys can be defined but are not enforced. Lack of enforced referential integrity means the application must maintain these relationships, which could lead to potential data integrity issues if not properly managed.</li><li>Data Consistency: Primary keys also enforce uniqueness in traditional databases ensuring no duplicate records are entered. As Snowflake does not enforce uniqueness through Primary Keys, there is a potential for duplicate data to be inserted which could lead to inconsistencies and errors in reporting or even processing.</li><li>Query Performance: Traditional databases rely on indexes to improve the performance of data retrieval operations. Snowflake manages data storage and retrieval without traditional indexes, using mico-partitioning and clustering features. However, migrating from systems that completely rely on indexes may need to re-examine their query performance or redesign the existing framework.</li><li>Application Logic Changes: Due to the lack of enforced constraints, business logic that was previously implemented at the database level via constraints may need to be moved into the application code or implemented via Snowflake features such as Streams and Tasks or by using Stored Procedures.</li></ol><h3>Hybrid Tables</h3><p>A hybrid table is a type of table in Snowflake that is designed to handle both transactional and operational workloads. This table is optimized for small, random point reads and writes that require low latency and high throughput. A hybrid table supports unique and referential integrity constraint enforcement, which is crucial for transactional workloads.</p><p>Hybrid tables can be created using the same Snowflake database services since Hybrid tables are integrated into the existing Snowflake architecture. We can execute these tables in Snowflake just like regular tables. The best part of Hybrid tables is that we can run hybrid workloads that mix operational and analytical queries.</p><p>As per the Snowflake documentation, below is the architecture of the Hybrid tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/0*NfY2YjPHDB0W7cOd.png" /></figure><p>As per Snowflake, Hybrid tables are designed to optimize your query performance. They use a row store as the primary data store to ensure fast operational query performance. When you write data to a hybrid table, it is directly written into the rowstore. The data is then asynchronously copied into object storage to provide better performance and workload isolation for large scans, without affecting your ongoing operational workloads.</p><p>Additionally, some data may also be cached in columnar format in your warehouse, which offers better performance for analytical queries. You can simply execute SQL statements against the logical hybrid table and Snowflake’s query optimizer will decide where to read data from, ensuring the best performance. You can view your data consistently without having to worry about the underlying infrastructure.</p><h4>Features</h4><p>Hybrid tables provide some additional features that are not supported by other Snowflake table types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0b4DiyNB_B--5M0mOa0tA.png" /></figure><h4>Limitations</h4><ul><li>Hybrid tables are not available in Azure or Google Cloud Platform (GCP).</li><li>Hybrid tables are not available in SnowGov Regions.</li><li><strong>Clustering keys</strong> are not supported in hybrid tables. Data in hybrid tables is ordered by primary key.</li><li><strong>Constraints</strong> can only be defined at table creation and are enforced at the row level. You cannot alter a column to be unique.</li><li>Constraints are not enforced at the statement or transaction level (that is, deferred constraints).</li><li>You are limited to storing <strong>500GB</strong> of data in hybrid tables in your account.</li><li>You cannot modify an index on an existing hybrid table. You cannot create an index on column(s) of semi-structured data type (ARRAY, OBJECT, VARIANT).</li><li><strong>TIMESTAMP</strong> columns are supported, but not when part of a composite key in a base table or index while comparisons (for example, WHERE)</li><li>It is not possible to create a hybrid table in a provider account, nor can a hybrid table be included in a view that is shared through the Native App.</li><li>You cannot use hybrid tables if your Snowflake account is enabled to use<strong> periodic rekeying</strong>.</li><li>You can execute up to approximately <strong>1,000 operations per second</strong> against hybrid tables in your account for a balanced 80%/20% read/write workload. If you exceed this limit, Snowflake might reduce your throughput.</li><li><a href="https://docs.snowflake.com/en/user-guide/account-replication-intro"><strong>Replication</strong></a> of hybrid tables is currently not supported. If a primary database contains a hybrid table, the refresh operation fails.</li><li><strong>UNDROP</strong> is not supported for hybrid tables.</li><li>The <strong>SQL API</strong> is not supported for hybrid tables.</li><li>It is recommended to use CREATE TABLE … AS SELECT for bulk loading data into a hybrid table. This option is optimized for performance and is approximately 10 times faster than other options, such as COPY or INSERT INTO … SELECT, when loading multiple millions of records.</li><li>When using DML commands to change a small number of rows, optimize performance by using INSERT, UPDATE, or DELETE statements instead of MERGE.</li></ul><h4><strong>Performance of Hybrid tables</strong></h4><p>Hybrid tables are a powerful tool that allows for speedy and efficient handling of up to 1000 operations per second. They offer double-digit millisecond latency, making them ideal for both point operations and analytical queries. Whether you need to quickly retrieve specific information or perform complex data analysis, hybrid tables can provide the performance and speed you need to get the job done effectively.</p><p>During real-time use, I’ve noticed a latency of at least three digits for complex operations. However, this is still acceptable as the difference between one or two hundred milliseconds is negligible.</p><h4><strong>Cost of Hybrid Tables</strong></h4><ul><li><strong>Hybrid table storage</strong>: Cost for storage of hybrid tables depends on the amount of data that you are storing in hybrid tables. Storage cost is based on a flat monthly rate per gigabyte (GB). Below Snowflake consumption table covers unit pricing for hybrid table storage. Note that hybrid table storage is more expensive than traditional Snowflake storage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZ4sRt8ZyT2-4ydQ8pXzEw.png" /><figcaption>Table 3b — <a href="https://www.snowflake.com/legal-files/CreditConsumptionTable.pdf">Snowflake Consumption Table</a></figcaption></figure><ul><li><strong>Virtual warehouse compute</strong>: Queries against hybrid tables are executed through virtual warehouses. The consumption rate of a warehouse is the same for querying hybrid tables as it is for standard tables.</li><li><strong>Hybrid table requests</strong>: Because they use <a href="https://docs.snowflake.com/en/user-guide/cost-understanding-compute.html#label-serverless-credit-usage">serverless resources</a>, hybrid tables consume additional credits on the underlying row storage clusters. Your consumption of serverless resources is based on the amount of data that is read from or written to storage clusters. Below Snowflake consumption table, which covers serverless resource unit pricing for hybrid table requests. Because hybrid tables store data in pages, even small read or write operations incur a minimum 4 KB of hybrid table request usage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hggAfnteD_qzx3qi1jh5sA.png" /><figcaption>Table 5 — <a href="https://www.snowflake.com/legal-files/CreditConsumptionTable.pdf">Snowflake consumption table</a></figcaption></figure><h4>Usage with Examples</h4><pre>-- Create hybrid table<br>CREATE OR REPLACE HYBRID TABLE employee (<br> id NUMBER PRIMARY KEY AUTOINCREMENT START 1 INCREMENT 1,<br> name VARCHAR NOT NULL,<br> city VARCHAR NOT NULL<br>);</pre><pre>-- Insert data into hybrid table<br>INSERT INTO employee VALUES(1, &#39;Peter&#39;, &#39;Seattle&#39;);<br>INSERT INTO employee VALUES(2, &#39;John&#39;, &#39;London&#39;);<br>INSERT INTO employee VALUES(3, &#39;Harry&#39;, &#39;Dubai&#39;);<br>INSERT INTO employee VALUES(4, &#39;Wilson&#39;, &#39;Melborne&#39;);</pre><p>Table creation took around 400ms and loading all the above records into the table took 75ms.</p><p>I created the above statement while the warehouse was running. However, if you run the statement while the warehouse is suspended, the insert statement may take around 1.2 seconds.</p><pre>UPDATE employee SET name = &#39;Kyle&#39; WHERE id = 6;<br><br>DELETE FROM employee WHERE id = 6;<br><br>SELECT * from employee;</pre><p>The Delete and Select statements took around 600ms and the Update statement took around 75ms with the running warehouse.</p><h4>Conclusion</h4><p>Hybrid tables can be a great solution if you want to move from a relational database that depends on multiple constraints such as primary keys, foreign keys, and indexes to Snowflake, while still keeping your existing logic and pipelines.</p><p>However, it’s important to note that there may be some limitations that could impact the efficiency and scalability of your system. Overall, hybrid tables offer a powerful and flexible solution for those who need to move to Snowflake without completely abandoning their existing data structures and logic.</p><p><strong><em>Before you leave:</em></strong></p><p>If you liked this article, please give it a few claps, <a href="https://imharmanbhatia.medium.com/">follow me</a> and thus receive all updates about new publications.</p><p>I hope this helps. Kindly let me know if you have any questions.</p><blockquote><em>I offer consultancy services for various areas, including data warehouse migrations, cost reduction strategies, data management practices, and data modelling expertise. If you require assistance or guidance in any of these domains, feel free to reach out, and I’ll be more than happy to provide my expertise and support.</em></blockquote><p><em>Email — imharmanbhatia@gmail.com</em></p><p>Please feel free to reach out via <a href="/service/mailto:imharmanbhatia@gmail.com">email</a> or <a href="https://in.linkedin.com/in/imharmanbhatia">LinkedIn</a>.</p><p>References —</p><p><a href="https://docs.snowflake.com/en/user-guide/tables-hybrid">Hybrid tables | Snowflake Documentation</a></p><p><a href="https://docs.snowflake.com/en/user-guide/tables-hybrid-cost">https://docs.snowflake.com/en/user-guide/tables-hybrid-cost</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=849cdbbb51d7" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/data-migration-made-easy-with-snowflake-hybrid-tables-849cdbbb51d7">Data Migration Made Easy with Snowflake Hybrid Tables</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Dynamic Tables: Materializing Results for Warehouse Cost Reduction]]></title>
            <link>https://imharmanbhatia.medium.com/snowflake-dynamic-tables-materializing-results-for-warehouse-cost-reduction-9ab68468dfdf?source=rss-12e4d7a478d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ab68468dfdf</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[dynamic-table]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Harman Bhatia]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 08:58:59 GMT</pubDate>
            <atom:updated>2023-07-11T08:58:59.837Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1HRPYB9jAF4B0vtxhhNgA.png" /></figure><p>Picture this: You have a query, and you want to materialize its results in a table. Instead of going through the hassle of creating a separate target table, writing transformation code, and manually updating the data, Snowflake’s dynamic tables come to the rescue.</p><h3>What are Dynamic tables in Snowflake?</h3><p>Dynamic tables serve as a remarkable solution by effortlessly materializing the results of your specific query. Often, we encounter extensive transformation logic involving multiple joins and union statements, which we typically address by creating new tables or views. However, when these queries or transformations need to be frequently used, they consume substantial computing resources. Thankfully, with the advent of dynamic tables, we now have the ability to materialize these complex transformations or query logic. This not only conserves computing power but also enhances the efficiency of our processes.</p><p>Dynamic Tables revolutionize the process of creating and managing data pipelines, providing teams with a seamless experience and the assurance to build robust pipelines for production. Previously, data engineers had to rely on Streams, Tasks, and manual management of database objects (tables, streams, tasks, and SQL DML code) to construct data pipelines in Snowflake. However, with the introduction of Dynamic Tables, the process becomes significantly simplified. Take a look at the following diagram for a visual representation of this streamlined approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*UeK5ldpSEyQt2VGZ.png" /><figcaption>[Diagram representation of Dynamic Tables]</figcaption></figure><h3>Why did I start using Snowflake Dynamic Tables?</h3><p>Here are some reasons why I started implementing the dynamic tables —</p><ul><li>We have multiple complex Snowflake views that are built using complicated logic and involve numerous tables and views. These views are essential for our daily tasks, but because they are quite complex, they take a long time to process and use up a lot of computing resources. One such example is the creation of Fact views.</li><li>To enhance efficiency and reduce costs, we decided to materialize these complex views. By materializing the views, we aim to accelerate our processes and minimize resource consumption. This approach will enable us to store pre-computed results, resulting in faster data retrieval and reduced computing expenses.</li><li>Furthermore, these views serve as the foundation for generating reports on Looker, which are accessed by various stakeholders within the company. However, if the views are complex and take a significant amount of time to load, it directly impacts the speed and responsiveness of the Looker reports for these stakeholders.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3fTcqCcXA3y0I8P6ZttAA.png" /></figure><h3>When to use Dynamic tables with use cases?</h3><p><strong>1. You don’t want to write your own code to track data dependencies and manage the refreshes of data:</strong></p><p><strong>Use case:</strong> Suppose you have a complex data pipeline with multiple dependent tables. By leveraging dynamic tables, you can automate the tracking of data dependencies and refresh schedules, saving you the effort of writing and maintaining custom code for these tasks.</p><p><strong>2. You want to avoid the added complexity of streams and tasks:</strong></p><p><strong>Use case: </strong>If you have a scenario where using streams and tasks to manage data updates is overly complex for your needs, dynamic tables provide a simpler alternative. You can materialize the results of your queries without the additional overhead of managing streams and tasks.</p><p><strong>3. You don’t need fine-grained control over the schedule of refreshes:</strong></p><p><strong>Use case:</strong> Let&#39;s say you have a use case where the specific schedule of data refreshes is not critical. Dynamic tables offer a convenient solution by handling the refreshes automatically, relieving you from the need to manage and configure granular refresh schedules.</p><p><strong>4. You need to materialize the results of a query of multiple base tables:</strong></p><p><strong>Use case:</strong> Imagine you have a complex query involving multiple base tables and you frequently rely on the results of this query. By utilizing dynamic tables, you can materialize these query results, allowing for faster access and reducing the computational overhead of executing the query repeatedly.</p><p><strong>5. You don’t need to use query constructs currently unsupported for dynamic tables:</strong></p><p><strong>Use case:</strong> In situations where you have queries that rely on unsupported query constructs like stored procedures, non-deterministic functions (not listed in the supported functions documentation), external functions, or user-defined functions (UDFs), dynamic tables may not be suitable. In such cases, alternative methods would need to be considered to materialize and optimize the query results.</p><h3>Privileges Required for Creating Dynamic Tables</h3><p>This is the <strong>most important </strong>part of dynamic tables. Creating dynamic tables requires specific privileges to be granted. These privileges are crucial for managing and manipulating dynamic tables effectively.</p><p>To create a dynamic table, it is necessary to possess the following privileges:</p><ol><li>USAGE privilege on the database and schema where the table will be created.</li><li>CREATE DYNAMIC TABLE privilege on the schema where the table will be created.</li><li>SELECT privilege on the existing tables and views that will be queried to populate the dynamic table.</li><li>USAGE privilege on the warehouse will be utilized for refreshing the table.</li></ol><p>Moreover, to query a dynamic table or create a dynamic table that queries another dynamic table, the following privilege is required:</p><ul><li>SELECT privilege on the dynamic table itself.</li></ul><p><strong>Before proceeding with the creation of dynamic tables, it is crucial to ensure that the aforementioned privileges are granted and each point is adequately addressed. Confirm that the necessary privileges have been assigned to the user or role to prevent any authorization issues during the creation and querying of dynamic tables.</strong></p><h3>How to create Dynamic Tables?</h3><p>To create a dynamic table, you can use the CREATE DYNAMIC TABLE command, which involves specifying the query to be used, the desired lag of the data, and the warehouse to be utilized for performing the refreshes.</p><p>Here’s an example syntax for creating a dynamic table:</p><pre>CREATE OR REPLACE DYNAMIC TABLE dynamic_table_name<br>  LAG = &lt;lag_value&gt; -- 1 minute is the minimum lag time.<br>  WAREHOUSE = warehouse_name <br>  AS<br>    &lt;query&gt;;</pre><ul><li>dynamic_table_name: This is the name you want to assign to the dynamic table.</li><li>&lt;query&gt;: Replace this placeholder with the actual query that retrieves the data you wish to materialize.</li><li>&lt;lag_value&gt;: Specify the desired lag time (in days) for the data in the dynamic table. This determines how often the dynamic table is refreshed with the latest data.</li><li>warehouse_name: Provide the name of the Snowflake warehouse that will be used for performing the refreshes of the dynamic table.</li></ul><p>Once the dynamic table is created, it will automatically refresh based on the specified lag value, ensuring the data remains up-to-date.</p><p>Please find the below example of creating the dynamic tables.</p><pre>CREATE OR REPLACE DYNAMIC TABLE fact_readings<br>  LAG = &#39;1 minutes&#39; -- 1 minute is the minimum lag time.<br>  WAREHOUSE = dynamic_table_warehouse <br>  AS<br>    SELECT reading_id, meter_name FROM fact_readings;</pre><p>Similar to a materialized view, the columns present in a dynamic table are determined by the columns specified in the SELECT statement used during its creation. If any columns are expressions, it is necessary to provide aliases for those columns within the SELECT statement.</p><h3>Monitoring Dynamic Tables</h3><p>To obtain a list of dynamic tables within a schema and gather information about a specific dynamic table, there are multiple ways:</p><ol><li>Using Snowsight</li><li>Using SQL command</li></ol><p>In Snowsight, you can view the list of dynamic tables under</p><p><strong>Data → Databases → Schema → Dynamic Tables</strong></p><p>You can view the details about a specific dynamic table by selecting the dynamic table under the Dynamic Tables tab. The Dynamic Table details page will appear.</p><p>Furthermore, within the dynamic table details page, you will find various tabs that offer valuable insights into the dynamic table:</p><ol><li>The Graph tab showcases the directed acyclic graph (DAG) containing the dynamic table.</li><li>The Refresh History tab provides a comprehensive view of the refresh history, allowing you to track and monitor the refreshes of the dynamic table.</li></ol><p>If you want to view the list of dynamic tables using SQL command, use the SHOW DYNAMIC TABLES command.</p><pre>SHOW DYNAMIC TABLES LIKE &#39;fact_%&#39; IN SCHEMA factdb.myschema;</pre><p>To obtain information regarding the columns within a dynamic table, you can utilize the DESCRIBE DYNAMIC TABLE command. For instance, if you wish to list the columns present in the dynamic table named “fact_readings,” you can execute the following command:</p><pre>DESC DYNAMIC TABLE product;</pre><h3>How to Drop a Dynamic Table?</h3><p>To remove a dynamic table, you have two options: Snowsight or SQL commands.</p><p>Using Snowsight:</p><ol><li>Navigate to the dynamic table details page.</li><li>Click on the More menu, located in the upper-right corner of the page.</li><li>Select the “Drop” option.</li></ol><p>Using SQL:</p><ol><li>Employ the DROP DYNAMIC TABLE command.</li><li>For instance, if you want to drop the dynamic table named “product,” execute the following SQL command:</li></ol><pre>DROP DYNAMIC TABLE fact_readings;</pre><p>As Dynamic Tables are presently accessible in a private preview, a comprehensive understanding of their costing, performance, and efficiency aspects will be gained upon the release of the public version. In forthcoming articles, I will provide additional insights, recommendations, updates, and use cases to further illuminate the capabilities and benefits of Dynamic Tables. Stay tuned for more valuable information and analysis in the upcoming content.</p><p><strong><em>Before you leave:</em></strong></p><p>If you liked this article, don’t forget to give me a few claps, <a href="https://imharmanbhatia.medium.com/">follow me</a> and thus receive all updates about new publications.</p><p>I hope this helps. Let me know if you have more questions.</p><blockquote>I offer consultancy services for various areas, including data warehouse migrations, cost reduction strategies, data management practices, and data modelling expertise. If you require assistance or guidance in any of these domains, feel free to reach out, and I’ll be more than happy to provide my expertise and support.</blockquote><p><em>Email — imharmanbhatia@gmail.com</em></p><p>Please feel free to reach out via email, <a href="https://in.linkedin.com/in/imharmanbhatia">LinkedIn</a> or <a href="https://twitter.com/harmanbhatia101">Twitter</a>.</p><p>References —</p><p><a href="https://www.snowflake.com/blog/dynamic-tables-delivering-declarative-streaming-data-pipelines/">https://www.snowflake.com/blog/dynamic-tables-delivering-declarative-streaming-data-pipelines/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ab68468dfdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgres to Snowflake — Migrate Real-time and Historical data]]></title>
            <link>https://imharmanbhatia.medium.com/postgres-to-snowflake-migrate-real-time-and-historical-data-404176bbacc9?source=rss-12e4d7a478d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/404176bbacc9</guid>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Harman Bhatia]]></dc:creator>
            <pubDate>Wed, 05 Oct 2022 10:28:26 GMT</pubDate>
            <atom:updated>2022-10-05T10:28:26.377Z</atom:updated>
            <content:encoded><![CDATA[<h3>Postgres to Snowflake — Migrate Real-time and Historical data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27YttOrR-9RRCbvqg1_EwQ.png" /><figcaption>Postgres to Snowflake</figcaption></figure><p>Cloud data warehouse like Snowflake is designed for scalable business intelligence and analytics. There are various reasons to move from a traditional data warehouse to a cloud-based data warehouse, such as to handle big data and improve speed and performance. However, Our major reason for this migration was to accommodate end users. We want our users to run multiple queries against terabytes of data simultaneously and receive results in seconds.</p><p>In Postgres hosted on AWS RDS, the data retrieval time was <strong>13 minutes 23 seconds for 800k records</strong>. On the other hand, I ran the same query on Snowflake and got the result in just <strong>9 seconds.</strong></p><p>One of our challenges while migration was to keep the existing infrastructure running on Postgres as is and replicate the changes happening on Postgres DB to Snowflake within seconds. I tried multiple solutions using the Kinesis data stream and Firehose and wrote the transformations using Lambda functions. The process was quite complex, and the latency was high due to the multiple processes involved. As our ETL was already running on Postgres, I just had to replicate the historical and incremental data from Postgres to Snowflake. So, I used the following tech stack to implement the solution.</p><h3>Tools &amp; Technologies used</h3><ol><li>RDS Postgres</li><li>Snowflake</li><li>AWS DMS</li><li>AWS S3</li><li>PgAdmin</li></ol><blockquote>Please note that the versions of the above tech stack play a vital role in the migration. I faced multiple issues due to the version mismatch and specific support of the particular version of the AWS service.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbZqFD8opGC8P94FI6CrnQ.png" /><figcaption>Enabling CDC with an AWS-managed PostgreSQL DB instance with AWS DMS</figcaption></figure><p>While configuring DMS, please use one engine version lower than the latest version, i.e. 3.4.6. I will remind you at every step regarding which versions and options to choose.</p><h4><strong>Why I choose AWS DMS?</strong></h4><p>AWS DMS is an AWS cloud service created to migrate data in a variety of ways: to the AWS cloud, from on-premises or cloud hosted data stores. AWS DMS can migrate all kinds of data ranging from relational databases, data warehouses, NoSQL databases, and other types of data stores. It is quite versatile and can handle one-time data migration or perform continual data replication with ongoing changes, syncing the source and target.</p><p>One of my major reason is the ease of scalability in future and the cost of migration compared with other awesome services like Fivetran and Matillion.</p><p><strong>Please follow the below steps </strong>and choose minimal extra options if you are implementing the pipeline for the first time to make the pipeline run. Once your POC pipeline is ready, you can easily configure the existing pipeline as per your need.</p><p>First, we will replicate the incremental and historical data from Postgres to AWS S3 and then we will create a pipeline to migrate the data from AWS S3 to Snowflake.</p><h3>Steps to replicate data from Postgres to AWS S3</h3><h4>Step 1 —</h4><p>First, login into your AWS account,</p><p><strong>Open RDS → Parameter Groups → Create Parameter Group.</strong></p><ol><li>Select DB family — Postgres along with its correct version.</li><li>In type, select DB Cluster Parameter Group.</li><li>Provide the Group Name as per your naming standards and <strong>Create.</strong></li><li>In the new Parameter Group, set the rds.logical_replication parameter in your DB CLUSTER parameter group to 1.</li><li>The wal_sender_timeout parameter ends replication connections that are inactive longer than the specified number of milliseconds. The default is 60000 milliseconds (60 seconds). Setting the value to <strong>0 (zero)</strong> disables the timeout mechanism and is a valid setting for DMS.</li><li>set the parameter shared_preload_libraries to pglogical in the same RDS parameter group.</li></ol><h4>Step 2 —</h4><ol><li>Apply Parameter Group to your DB Cluster under the<em> Additional Configuration.</em></li><li>Select almost instantaneous as an option and <strong>REBOOT</strong> the database.</li></ol><h4>Step 3—</h4><p>Go to PgAdmin (I was using PgAdmin4) and run the below queries. Please note that these queries should be executed as a superuser/admin.</p><ol><li>create extension pglogical;</li><li>SELECT * FROM pg_catalog.pg_extension</li><li>SELECT * FROM pg_create_logical_replication_slot(‘<em>replication_slot_name</em>’, ‘pglogical’);</li></ol><h4>Step 4 —</h4><p>Create an S3 bucket if you have not created one. While creating an S3 bucket, I recommend ACLs be disabled, blocking all public access and enabling server-side encryption(SSE-S3).</p><p><strong>Go to IAM → Policy → Create Policy.</strong></p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:DeleteObject&quot;,<br>                &quot;s3:PutObjectTagging&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::buckettest2/*&quot;<br>            ]<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:ListBucket&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::buckettest2&quot;<br>            ]<br>        }<br>    ]<br>}</pre><h4>Step 5—</h4><p><strong>Go to IAM → Role → Create Role</strong></p><ol><li>The IAM role has DMS (dms.amazonaws.com) added as a <em>trusted entity</em>. For the same, select AWS Service, select DMS from the other AWS services.</li><li>Attach the policy created above to your new role.</li><li>After providing the role name, Create the role.</li></ol><h4>Step 6 —</h4><p><strong>Go to DMS → Create a replication instance → select a lower engine version.</strong></p><ol><li>Select the VPC and Add subnets, if any.</li><li>Please make sure that if there is any Security group for RDS, select the specific port for inbound and Outbound open for all as required for DMS to export files into S3.</li><li>If you choose Multi-AZ production, do not choose AZ settings.</li><li>Create the instance.</li></ol><h4>Step 7 —</h4><p><strong>Go to Endpoints → Create an endpoint.</strong></p><ol><li>Select Source endpoint → select RDS DB instance.</li><li>In the Endpoint configuration, either provide access to Postgres manually by providing a username and password or select AWS Secret Manager if you have the setup ready.</li><li>KMS key as default.</li><li>In Test endpoint connection, select VPC → Select replication instance created above → test the connection → Create the endpoint.</li></ol><p><strong>Similarly, Create another endpoint.</strong></p><ol><li>Select Target endpoint → Target engine as AWS S3</li><li>Provide the ARN of the role created above.</li><li>Provide bucket name and bucket folder.</li><li>In Test endpoint connection, select VPC → Select replication instance created above → test the connection → Create the endpoint.</li></ol><h4>Step 8 —</h4><p><strong>Go to Migration task → Create Migration Task</strong></p><ol><li>Choose Replication Instance — the instance that we created above.</li><li>Select Source and Target endpoint — Source as Postgres and Target as AWS S3</li><li>Select Migration type — There will be three options: “<em>Migrate existing data”</em>, “ <em>Migrate existing data and replicate ongoing changes”</em>, and “<em>replicate data changes only”. </em>Select the option based on your requirement.</li><li>In Task settings, select “Do nothing” in the Target table preparation mode and keep other options to default settings. You can enable cloudwatch logs if you face any errors or you want to track the transaction logs.</li><li>In Table mappings, click on Add new selection rule. If you want to include or exclude a specific schema or table, you can replace % with the schema name &amp; table name. Select the action based on your requirement.</li><li>There are multiple transformation options available in DMS tasks. If you want to transform the output tables, such as adding prefixes or a column, then you can select the transformation action and its value.</li><li>I would recommend selecting “Enable premigration assessment run”. This assessment is helpful to test the connections and other correlations. You just need to provide the S3 bucket and AWS role we created above. Once you create the task, you can see the assessment report in your S3 bucket, or you can also check it in DMS tasks.</li><li>Create the Task. Once the premigration assessment report is successful, start the task.</li></ol><p>For each source table that contains records, AWS DMS creates a folder under the specified target folder (if the source table is not empty). AWS DMS writes all full load and CDC files to the specified Amazon S3 bucket. There will be two types of files in the folder —</p><ol><li>Historical files — These files will have the prefix “LOAD”.</li><li>Incremental files — These files will have the name as the current timestamp.</li></ol><p>AWS DMS names files created during a full load using an incremental hexadecimal counter — for example, LOAD00001.csv, LOAD00002…, LOAD00009, LOAD0000A, and so on for .csv files. AWS DMS names CDC files using timestamps, for example, 20141029–1134010000.csv.</p><p>When you use AWS DMS to replicate data changes using a CDC task, the first column of the .csv or .parquet output file indicates how the row data was changed as shown for the following .csv file.</p><pre>I,101,Smith,Bob,4-Jun-19,Vancouver <br>U,101,Smith,Bob,8-Oct-21,London<br>U,101,Smith,Bob,13-Mar-22,Texas<br>D,101,Smith,Bob,13-Mar-22,Toronto</pre><p>Here, I — Insert, U — Update, D — Delete</p><p>Now, let’s create the pipeline from AWS S3 to Snowflake using Snowpipe, Tasks and Streams. Snowflake documentation is easy to understand and helpful in creating the connections between AWS S3 and Snowflake</p><h3>Steps to replicate data from AWS S3 to Snowflake</h3><p>Before starting with the steps to migrate data, create the tables in Snowflake as per our data files in AWS S3.</p><blockquote>If you are <strong>migrating historical data,</strong> create the table in Snowflake without any constraints except Not Null. Please take care of date and timestamp data types as most of the other data types are the same in Postgres and Snowflake.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTuoVXPhtBXYR-RK0OCmhA.png" /><figcaption>data types</figcaption></figure><blockquote>If you are <strong>migrating incremental/CDC data, </strong>create the tables with an extra column that DMS generates to identify if it is an Insert, Update or Delete. For example: if your table has four columns — id, name, email, phone, then add column at the start(say status). Now, the columns of your table would be — status, id, name, email, phone. I recommend to add the postfix to the table name, such as &lt;table&gt;_stg.</blockquote><p>If you want to create the final table with all the updated records, create another table without the status column. This will be your updated table with all the latest transaction changes applied. For the same, we will use tasks and streams. Now, follow the below steps to migrate the data from AWS S3 to Snowflake.</p><h4>Step 1 — Configuring access to AWS S3.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qcaXV9DQiOnWgmmg.png" /></figure><ol><li>Log into the AWS Management Console.</li><li>From the home dashboard, choose <strong>Identity &amp; Access Management</strong> (IAM)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CHt4S0Wio87jOp_7.png" /></figure><p>3. Choose <strong>Account settings</strong> from the left-hand navigation pane.</p><p>4. Expand the <strong>Security Token Service Regions</strong> list, find the AWS region corresponding to the <a href="https://docs.snowflake.com/en/user-guide/intro-regions.html">region</a> where your account is located, and choose <strong>Activate</strong> if the status is <strong>Inactive</strong>.</p><p>5. Choose <strong>Policies</strong> from the left-hand navigation pane.</p><p>6. Click <strong>Create Policy </strong>and then Click the <strong>JSON</strong> tab.</p><p>7. Add a policy document that will allow Snowflake to access the S3 bucket and folder.</p><pre>{<br>    <strong>&quot;Version&quot;:</strong> &quot;2012-10-17&quot;,<br>    <strong>&quot;Statement&quot;:</strong> [<br>        {<br>            <strong>&quot;Effect&quot;:</strong> <strong>&quot;Allow&quot;</strong>,<br>            <strong>&quot;Action&quot;:</strong> [<br>              &quot;s3:GetObject&quot;,<br>              &quot;s3:GetObjectVersion&quot;<br>            ],<br>            <strong>&quot;Resource&quot;:</strong> &quot;arn:aws:s3:::&lt;bucket&gt;/&lt;prefix&gt;/*&quot;<br>        },<br>        {<br>            <strong>&quot;Effect&quot;:</strong> <strong>&quot;Allow&quot;</strong>,<br>            <strong>&quot;Action&quot;:</strong> [<br>                &quot;s3:ListBucket&quot;,<br>                &quot;s3:GetBucketLocation&quot;<br>            ],<br>            <strong>&quot;Resource&quot;:</strong> &quot;arn:aws:s3:::&lt;bucket&gt;&quot;,<br>            <strong>&quot;Condition&quot;:</strong> {<br>                <strong>&quot;StringLike&quot;:</strong> {<br>                    &quot;s3:prefix&quot;: [<br>                        &quot;&lt;prefix&gt;/*&quot;<br>                    ]<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>8. Click <strong>Review policy</strong>.</p><p>9. Enter the policy name (e.g. snowflake_access) and an optional description. Click <strong>Create policy</strong>.</p><h4><strong>Step 2 — </strong>Create the IAM Role in AWS</h4><ol><li>Go to <strong>AWS → IAM → Roles → Create Role.</strong></li><li>Select <strong>AWS account</strong> as the trusted entity type.</li></ol><p>3. Later, you will modify the trusted relationship and grant access to Snowflake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iD34V5kiSEGH7O0EDuzeRg.png" /></figure><p>4. Select the <strong>Require external ID</strong> option. Enter a dummy ID such as 0000. Later, you will modify the trusted relationship and specify the external ID for your Snowflake stage. An external ID is required to grant access to your AWS resources (i.e. S3) to a third party (i.e. Snowflake).</p><p>5. <strong>Next</strong>, Locate the policy you created above and select that policy.</p><p>6. Enter a name and description for the role, and click the <strong>Create role</strong> button.</p><p>You have now created an IAM policy for a bucket, created an IAM role and attached the policy to the role. Record the <strong>Role ARN</strong> value located on the role summary page. In the next step, you will create a Snowflake integration that references this role.</p><h4>Step 3 — Create a Cloud Storage Integration in Snowflake</h4><p>Create a storage integration using the CREATE STORAGE INTEGRATION command. A storage integration is a Snowflake object that stores a generated identity and access management (IAM) user for your S3 cloud storage, along with an optional set of allowed or blocked storage locations (i.e. buckets).</p><blockquote>CREATE STORAGE INTEGRATION s3_int<br> type = external_stage<br> storage_provider = &#39;S3&#39;<br> enabled = true<br> storage_aws_role_arn = &#39;arn:aws:iam::001234567890:role/myrole&#39;<br> storage_allowed_locations = (&#39;s3://mybucket1/mypath1/&#39;, &#39;s3://mybucket2/&#39;)<br> storage_blocked_locations = (&#39;s3://mybucket1/mypath3/&#39;, &#39;s3://mybucket2/mypath4/&#39;);</blockquote><p>Please note that the S3 bucket path in the Snowflake role created above should include the storage_allowed_locations in the storage integration. I recommend providing access to the complete bucket in the IAM policy if you are using multiple locations in AWS S3.</p><h4>Step 4 — Retrieve the AWS IAM User for your Snowflake Account</h4><ol><li>Execute the DESCRIBE INTEGRATION command to retrieve the ARN for the AWS IAM user that was created automatically for your Snowflake account:</li></ol><pre>DESC INTEGRATION s3_int;</pre><p>2. Copy the values of STORAGE_AWS_IAM_USER_ARN and STORAGE_AWS_EXTERNAL_ID</p><h4>Step 5 — Grant the IAM User Permissions to Access Bucket Objects</h4><ol><li>Go to <strong>AWS → IAM → Roles → Select the snowflake role.</strong></li><li>Click on the <strong>Trust relationships</strong> tab and click the <strong>Edit trust relationship</strong> button.</li><li>Modify the policy document with the DESC STORAGE INTEGRATION output values you copied from the last step.</li><li><strong>Policy document for IAM role</strong></li></ol><pre>{<br>  <strong>&quot;Version&quot;:</strong> &quot;2012-10-17&quot;,<br>  <strong>&quot;Statement&quot;:</strong> [<br>    {<br>      <strong>&quot;Sid&quot;:</strong> <strong>&quot;&quot;</strong>,<br>      <strong>&quot;Effect&quot;:</strong> <strong>&quot;Allow&quot;</strong>,<br>      <strong>&quot;Principal&quot;:</strong> {<br>        <strong>&quot;AWS&quot;:</strong> &quot;&lt;snowflake_user_arn&gt;&quot;<br>      },<br>      <strong>&quot;Action&quot;:</strong> &quot;sts:AssumeRole&quot;,<br>      <strong>&quot;Condition&quot;:</strong> {<br>        <strong>&quot;StringEquals&quot;:</strong> {<br>          &quot;sts:ExternalId&quot;: &quot;&lt;snowflake_external_id&gt;&quot;<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p>Where:</p><p>snowflake_user_arn is the STORAGE_AWS_IAM_USER_ARN value you recorded.</p><p>snowflake_external_id is the STORAGE_AWS_EXTERNAL_ID value you recorded.</p><p>5. Click the <strong>Update Trust Policy</strong> button. The changes are saved.</p><h4>Step 6 — Setting up SQS notifications</h4><p>As the data files are loaded in an S3 stage, an S3 event notification informs Snowpipe via an SQS queue that files are ready to load. Snowpipe copies the files into a queue. A Snowflake-provided virtual warehouse loads data from the queued files into the target table based on parameters defined in the specified pipe.</p><ol><li>Create an external Stage</li></ol><pre>use schema snowpipe_db.public;<br><br>create stage mystage<br>  URL = &#39;s3://mybucket/load/files&#39;<br>  storage_integration = my_storage_int;</pre><p>2. Create a Pipe with Auto-Ingest Enabled</p><p>Here, the important point to note is that you need to use the stg table with an additional status column.</p><pre>create pipe snowpipe_db.public.mypipe auto_ingest=true as<br>  copy into snowpipe_db.public.mytable_stg<br>  from @snowpipe_db.public.mystage<br>  file_format = (type = &#39;JSON&#39;);</pre><p>The AUTO_INGEST=true the parameter specifies to read event notifications sent from an S3 bucket to an SQS queue when new data is ready to load.</p><p>3. Execute the SHOW PIPES command:</p><pre>show pipes;</pre><p>Note the ARN of the SQS queue for the stage in the notification_channel column. <strong>Copy the ARN to a convenient location like a notepad.</strong></p><p>4. Log into the Amazon S3 console. In the <strong>Buckets</strong> list, choose the name of the bucket that you want to enable events for.</p><p>5. Choose <strong>Properties</strong>. Navigate to the <strong>Event Notifications</strong> section and choose to <strong>Create event notification</strong>.</p><p>5. Configure an event notification for your S3 bucket using the instructions provided in the <a href="https://docs.aws.amazon.com/AmazonS3/latest/user-guide/enable-event-notifications.html">Amazon S3 documentation</a>. Complete the fields as follows:</p><ul><li><strong>Name</strong>: Name of the event notification (e.g. Auto-ingest Snowflake).</li><li><strong>Events</strong>: Select the <strong>ObjectCreate (All)</strong> option.</li><li><strong>Send to</strong>: Select <strong>SQS Queue</strong> from the dropdown list.</li><li><strong>SQS</strong>: Select <strong>Add SQS queue ARN</strong> from the dropdown list.</li><li><strong>SQS queue ARN</strong>: Paste the SQS queue name from the SHOW PIPES output.</li></ul><p>Snowpipe with auto-ingest is now configured!</p><h4>Now, if you want to create an updated table with all the latest records, please follow the below steps.</h4><h4>Step 1 — Create a Stream on the STG tables.</h4><pre>CREATE OR REPLACE STREAM table_stg_stream ON TABLE public.table_stg;</pre><pre>SHOW STREAMS;</pre><p>To check the stream functionality we can insert data into the staging table and query the stream to check if the data insertion is captured by the stream.</p><pre>INSERT OVERWRITE INTO table_stg  <br>VALUES (&#39;I&#39;, 1, &#39;Tom&#39;,&#39;tom.harry@john.com&#39;, 04129);</pre><pre>SELECT * FROM table_stg_stream;</pre><p>Snowflake streams are quite vast and could be used for various purposes, such as transaction logs, data merge, ETL pipeline and many more. In this blog, I am covering the basic streams as the data in the staging table will be loaded through AWS DMS.</p><h4>Step 2— Create a task to merge the stream with the final table.</h4><p>The task is created to merge the changes captured by the stream with the final_table. I have scheduled the task to 1 minute, i.e. task will run every minute as per the condition provided. One minute is the minimum time and we cannot reduce the time to less than a minute.</p><pre><br>CREATE OR REPLACE TASK all_data_changes<br>    WAREHOUSE = COMPUTE_WH<br>    SCHEDULE = &#39;1 MINUTE&#39;<br>    WHEN SYSTEM$STREAM_HAS_DATA(&#39;table_stg_stream&#39;)<br>    AS <br>MERGE INTO public.final_table  -- Target table to merge changes from a source table<br>USING ( SELECT *<br>        FROM table_stg_stream<br>       ) S<br>ON F.user_id=S.user_id<br>when matched                        -- DELETE condition<br>    and s.status = &#39;D&#39;<br>    then delete                   <br>when matched                        -- UPDATE condition<br>    and s.status= &#39;U&#39;      <br>    then update <br>    set f.username = s.username,<br>        f.email= s.email,<br>        f.phone=s.phone<br>when not matched <br>    and S.METADATA$ACTION =&#39;INSERT&#39;<br>    then insert <br>    (user_id, username, email, phone)<br>    values<br>    (s.user_id, s.username, s.email, s.)<br>    <br>    <br>ALTER TASK all_data_changes RESUME;<br>SHOW TASKS;</pre><p>After creating the task, It is important to run the ALTER TASK statement to start the execution of the task.</p><p>Now, you are ready to test the complete end-to-end pipeline by updating the record in Postgres and querying it in Snowflake.</p><p><strong><em>Before you leave:</em></strong></p><p>If you liked this article, don’t forget to give me a few claps, <a href="https://imharmanbhatia.medium.com/">follow me</a> and thus receive all updates about new publications.</p><p>Hope this helps. Let me know if you have more questions.</p><p><em>Email — imharmanbhatia@gmail.com</em></p><p>Please feel free to reach out via email, <a href="https://in.linkedin.com/in/imharmanbhatia">LinkedIn</a> or <a href="https://twitter.com/harmanbhatia101">Twitter</a>.</p><h3>References</h3><ol><li><a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.PostgreSQL.html#CHAP_Source.PostgreSQL.RDSPostgreSQL">Using a PostgreSQL database as an AWS DMS source</a></li><li><a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.S3.html">Using Amazon S3 as a target for AWS Database Migration Service</a></li><li><a href="https://docs.snowflake.com/en/user-guide/data-load-snowpipe-auto-s3.html#automating-snowpipe-for-amazon-s3">Automating Snowpipe for Amazon S3</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=404176bbacc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Best Practices]]></title>
            <link>https://imharmanbhatia.medium.com/snowflake-best-practices-1eca6127403?source=rss-12e4d7a478d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1eca6127403</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[snowflake-computing]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <dc:creator><![CDATA[Harman Bhatia]]></dc:creator>
            <pubDate>Fri, 19 Mar 2021 15:19:54 GMT</pubDate>
            <atom:updated>2021-03-19T15:19:54.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*WTiuTP3sCFUm18hGXNvO4g.png" /></figure><h3>1- Introduction</h3><p>Snowflake is one of the few enterprise-ready cloud data warehouses that brings simplicity without sacrificing features. It automatically scales, both up and down, to get the right balance of performance vs. cost. Snowflake’s claim to fame is that it separates compute from storage. This is significant because almost every other database, Redshift included, combines the two, meaning you must size for your largest workload and incur the cost that comes with it.</p><p>In this document, we will focus on some of the best practices based on Snowflake&#39;s recommendation and previous experience.</p><h3>2- Best Practice — Efficient Table Design</h3><p><strong>i. Choosing the appropriate data types helps in improving query performance.</strong></p><p>· Date and TimeStamp are stored more efficiently than VARCHAR on Snowflake.</p><p>· Snowflake recommends choosing a date or timestamp data type for storing date and timestamp fields instead of a character data type.</p><p><strong>ii. It is recommended to use Referential Integrity Constraints</strong></p><p>· They provide valuable metadata that users can use to understand the schema and the relationships defined between tables.</p><p>· In Snowflake, referral integrity constraints are not enforced by default. When created, they are disabled. NOT NULL is an exception and is enforced by default.</p><p><strong>iii. For big data sets, Clustering is a good practice and helps improve query performance.</strong></p><p>· One will have to manually run a DML statement to re-cluster a table.</p><p>· The existing data will be re-written in a different order upon re-clustering. Snowflake saves the previous order for 7 days to provide Fail-safe protection, one of Snowflake’s cloud data warehouse&#39;s most lauded features.</p><p>· Re-clustering a table on Snowflake costs additional dollars. This is directly proportional to the size of the data set that is re-ordered.</p><h3>3- Best Practice — Data Storage</h3><p>Snowflake provides an array of features for data that is stored. Continuous Data Protection (CDP) which includes Fail-Safe and Time Travel is given to all Snowflake accounts for no additional cost. This does not mean that CDP will not have an impact on your storage costs. On the contrary,</p><p>· Your account will be charged for all the data stored in schemas, tables, and databases created in your Snowflake architecture. Based on the data stored and the duration for which it is stored, CDP has an impact on the storage costs.</p><p>· Until the data leaves the Fail-safe state, storage costs will be incurred. This means that you pay for the data storage irrespective of whether it is in an Active, Time-travel, or Fail-safe State. Hence, it is important to make the right storage considerations.</p><h3>4- Best Practice — Data Staging</h3><p>To assist in loading bulk data into tables, Snowflake has a feature called stages where files that have the data to be loaded are staged.</p><p>· Snowflake allows both internal (within Snowflake) and external (S3, Azure) stages.</p><p>· No additional cost is charged for Time Travel and Fail-safe features for data stored in internal stages within Snowflake. However, standard data storage costs apply.</p><p>· While performing Snowflake ETL, it is a good practice to stage regular data sets by partitioning them into logical paths. This could include details such as source identifiers or geographical location, etc., along with the date when the data was written.</p><p>· Staging will allow you to take advantage of Snowflake’s parallel operations by letting you execute concurrent COPY statements that match a subset of files.</p><h3>5- Best Practice — Data Cloning</h3><p>Snowflake has a zero-copy cloning feature that gives an easy way to take a “snapshot” of any schema, table, or database.</p><p>· Cloning creates a derived copy of that object which initially shares the underlying storage. This can come in handy when creating instant backups.</p><p>· Cloning does not incur any additional costs if you do not need to make any changes to the cloned object.</p><h3>6- Best Practice — Data Loading Considerations</h3><p><strong>i. General File Sizing Recommendations</strong></p><p>· While performing Snowflake ETL, it is important to optimize the number of parallel loads into Snowflake. It is recommended to create compressed data files that are roughly 10 MB to 100 MB in size.</p><p>· Aggregate the smaller files to reduce processing overhead. Split the large files into several smaller files for faster load. This allows you to distribute the load between servers in the active Snowflake warehouse.</p><p><strong>ii. Data Size Limitations for Semi-Structured Data</strong></p><p>· The VARIANT data type has a 16 MB (compressed) size limit on the individual rows.</p><p>· For efficiency enhancement, while executing the COPY INTO &lt;table&gt; command it is recommended to enable the STRIP_OUTER_ARRAY file format option. This will load the records into separate table rows by removing the outer array structure.</p><p><strong>iii. Data Size Limitations of Parquet files</strong></p><p>It is recommended to split parquet files that are greater than 3GB in size into smaller files of 1GB or lesser for smooth loading. This will ensure that the loading does not timeout.</p><p><strong>iv. Preparing Delimited Text Files</strong></p><p>The following points must be considered while preparing CSV/Delimited text files for loading:</p><p>· Files must have data in ASCII format only. The default character set is UTF-8. However, additional encodings can be mentioned using the ENCODING file format option.</p><p>· Within the files, records and fields should be delimited by different characters. Note, that both should be a single (necessarily not the same) character. Pipe (|), caret (^), comma (,), and tilde (~) are common field delimiters. Often the line feed (n) is used as a row delimiter.</p><p>· Fields that have delimiter should be enclosed in single or double-quotes. If the data being loaded contains quotes, then those must be escaped.</p><p>· Fields that have carriage returns (r n) should be enclosed in single or double quotes too. In the windows system, carriage returns are commonly introduced along with a line feed character to mark the end of a line.</p><p>· Each row should have the same number of columns.</p><h3>7- Best Practice — Improving Load Performance</h3><p>· Use bulk loading to get the data into tables in Snowflake.</p><p>· Consider splitting large data files so the load can be efficiently distributed across servers in a cluster.</p><p>· Delete from internal stages files that are no longer needed. You may notice improved performance in</p><p>· addition to saving on costs.</p><p>· Isolate load and transform jobs from queries to prevent resource contention. Dedicate separate warehouses</p><p>· for loading and querying operations to optimize performance for each.</p><p>· Leverage the scalable compute layer to do the bulk of the data processing.</p><p>· Consider using SnowPipe in micro-batching scenarios.</p><h3>8- Best Practice — Data Caching</h3><p>While Caching is automatic behavior, there are two best practices you can implement to maximize cache usage and speed query performance.</p><p>· Firstly, when segmenting query workload, you should place users querying the same data on the same virtual warehouse. This maximizes the chances that data retrieved to the cache by one user will also be used by others.</p><p>· Finally, be aware that the result cache is completely independent of the virtual warehouse, and any query executed by any user on the account will be served from the result cache, provided the SQL text is the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*tnfcJhDPVZo27r0xVtdpSQ.png" /></figure><h3>9- Best Practice — Data Querying</h3><p><strong>i. Dedicated warehouse for Querying:</strong></p><p>· Snowflake automatically caches data in the Virtual Warehouse (local disk cache), so place users querying the same data on the same virtual warehouse. This maximizes the chances that data retrieved to the cache by one user will also be used by others. The suspending warehouse will erase this cache.</p><p>· Result Cache is maintained by the Global Services layer, any query executed by any user on the account will be served from the result cache, provided the SQL text is the same. Results are retained for 24 hours.</p><p>· Snowflake Query Profile feature helps us to analyze queries being run from BI tools as well. In case, you have multiple BI tools and common users, having a dedicated warehouse for each BI tool will help to identify queries generated from the BI tool.</p><h3>10- Best Practice — Warehouse Size</h3><p>Snowflake offers pay-per-second billing. They allow the different sizes of the warehouse (Large, X-Large, 2X-Large, etc.). Create separate warehouses for different environments such as development, testing, and production.</p><p>· For queries in development or testing environments, smaller warehouse sizes (such as X-Small, Small, Medium) may be enough.</p><p>· For queries in production environments, larger warehouse sizes (such as Large, X-Large, 2X-Large, etc.) may be enough and cost-effective.</p><p>· From a performance point of view, it is always better to create a separate warehouse for your data loading and query execution. Start with a smaller size and based on the performance, you can manually resize the warehouse.</p><p>· Increasing the size of a warehouse does <strong>not</strong> always improve data loading performance. Data loading performance is influenced more by the number of files being loaded (and the size of each file) than the size of the warehouse.</p><p>· Credit charges are calculated based on:</p><p>· The number of Clusters (if using a multi-cluster warehouse)</p><p>· The number of servers per cluster (a derivative of warehouse-size)</p><p>· The time duration that each cluster in each server runs for</p><h3>11- Best Practice — Warehouse Optimizations</h3><p><strong>i. Enable Auto-Suspend</strong></p><p>Make sure all virtual warehouses are set to auto-suspend. This way, when they are done processing queries, auto-suspend will turn off your virtual warehouses, and thus stop credit consumption.</p><p><strong>ii. Enable Auto-Resume</strong></p><p>Make sure all virtual warehouses are set to auto-resume. If you are going to implement auto-suspend and set appropriate timeout limits, enabling auto-resume is a must; otherwise, users will not be able to query the system.</p><p><strong>iii. Set Timeouts Appropriately for Workloads</strong></p><p>All virtual warehouses should have an appropriate timeout for their particular workload:</p><p>· For the task, data loading, and ETL/ELT warehouses set the timeout for suspension immediately upon completion.</p><p>· For BI and SELECT query warehouses, set the suspension timeout to 10 minutes in most situations to keep data caches warm for frequent access by end-users.</p><p>· For DevOps, DataOps, and data science warehouses, set the suspension timeout to 5 minutes because having a warm cache is not as important for ad hoc and highly unique queries.</p><p><strong>iv. Set Account Statement Timeouts</strong></p><p>Use the STATEMENT_QUEUED_TIMEOUT_IN_SECONDS and STATEMENT_TIMEOUT_IN_SECONDS parameters to automatically stop queries that are taking too long to execute, either due to a user error or a frozen cluster. Customize warehouse, account, session, and user timeout-level statements according to your data strategy for long-running queries.</p><p><strong>Here’s an example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*aBt6U725EbebVdv_xsrY3A.png" /></figure><p><strong>v. Drop Unused Tables</strong></p><p>You might have unused tables that are candidates to be dropped. Just make sure no one is querying these tables. In fact, you might want to make it mandatory to check all tables before deletion. (If you have Time Travel set up, you can un-drop a table if you make an error.) This is specific to the database context, so be sure to look at tables across your databases. Also, be mindful of tables used only because of DDLs.</p><p><strong>vi. Find Warehouses That Don’t Have Resource Monitors</strong></p><p>Resource monitors are a great way to proactively control workload budgets and prevent unexpected resource spikes. Resource monitors can help monitor both user usage and service account usage in Snowflake. First, you should have dedicated virtual warehouses for each of your loading, ELT, BI, reporting, and data science workloads as well as for other workloads. Accounts and warehouses can have total, yearly, monthly, weekly, and daily credit quotas.</p><p><strong>vii. Apply Resource Monitors</strong></p><p>You can use the UI or SQL to apply your resource monitor policy. Based on account preference settings, resource monitors can notify you when consumption reaches a lower threshold, and then suspend the warehouse or account at a higher threshold.</p><p><strong>Considerations for Resource Monitoring</strong></p><p>· We recommend setting monitors to notify you when a certain threshold of consumption is reached.</p><p>· When consumption approaches the maximum budgeted level, set the resource monitor to auto-suspend the warehouse or the entire account, allowing queries to complete but preventing future requests.</p><p>· Resource monitors can also be used to terminate all currently running queries and immediately suspend the resource or account. This setting is usually reserved for situations where a hard quota is exceeded.</p><p>· For customers that do not want to set hard limits, it’s still always a good idea to have notification monitors set on all warehouses in case of usage unexpectedly spikes. That way, all admins within the account will get an email or on-screen notification when thresholds are reached.</p><p>The following figure shows the resource monitor configuration screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*onIVXQ2c-hPF8ehX93bEog.png" /></figure><h3>12- Best Practice — Scaling Data Warehouse</h3><p><strong>i. Scale- Up</strong></p><p>Snowflake allows for a scale-up in the virtual data warehouse to better handle large workloads. When using scale-up to improve performance, make note of the following:</p><p>· Snowflake supports fast and easy adjustments to the warehouse-size to handle the workload.</p><p>· It can also automatically suspend or resume the scale-up, with complete transparency for the user.</p><p>Snowflake’s scale-up functionality supports the continually changing requirements for processing.</p><p><strong>ii. Scale-Out</strong></p><p>Snowflake supports the deployment of same-size clusters to support concurrency. Keep these points in mind for how scale-out can help performance optimization:</p><p>· As users execute queries, the virtual data warehouse automatically adds clusters up to a fixed limit.</p><p>· It can scale-up in a more controlled way instead of deploying one or more clusters of larger machines like legacy data platforms.</p><p>Snowflake automatically adjusts based on user queries, with automatic clustering during peak and off-hours as needed.</p><p><strong>iii. Enable Auto-Scaling</strong></p><p>If you are using an enterprise edition of Snowflake, multi-cluster warehouses should be configured to run in an Auto-scale mode, which enables Snowflake to automatically start and stop clusters as needed.</p><h3>13- Best Practice — Leverage Materialized Views</h3><p>Materialized views can improve the performance of queries that repeatedly use the same subquery results. Use materialized views when</p><p>· The query contains a small number of rows and/or columns relative to the base table</p><p>· The query contains results that require significant processing</p><p>· The query is against file-based data</p><p>· Results don’t change often</p><p>· Results are used often</p><p>· The query consumes a lot of resources</p><p>You can create a materialized view like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*Frf6XNC7QI9Vxf8eDH3K9A.png" /></figure><p>And use it like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*oCbA1MhbKD9xAYJHgX91rA.png" /></figure><p><strong>But be careful! There are some gotchas:</strong></p><p>· A background service automatically updates the materialized view after changes are made to the base table</p><p>· The maintenance of materialized views consumes credits</p><p>· Compare materialized views vs. scaling up compute to solve performance issues.</p><h3>14- Best Practice — Segment Data</h3><p>Snowflake caches data in the virtual data warehouse, but it’s still essential to segment data. Consider these best practices for data query performance:</p><p>· Group users with common queries in the same virtual data warehouse to optimize data retrieval and use.</p><p>· The Snowflake Query Profile supports query analysis to help identify and address performance concerns.</p><p>Snowflake draws from the same virtual data warehouse to support complex data science operations, business intelligence queries, and ELT data integration.</p><h3>15- Best Practice — Using Snowflake Query Profile</h3><p>The first step to Snowflake optimization is to discover the source of performance bottlenecks. Use Snowflake’s Query Profile tool to diagnose issues in slow-running queries. Like similar database management tools, Query Profile lets you explore how Snowflake executed your query and what steps in the process are causing slowdowns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*N9MNdTKWWkGIc1dFj8gdTw.png" /></figure><p>Once you have identified the nature of the problem, use these seven best practices to help optimize your query speed and overall Snowflake performance.</p><h3>16- Benefit from a range of Integrations and Partnerships</h3><p>Snowflake’s ecosystem is designed for flexibility, openness, and extensibility without exposure to security threats. That means you benefit from partnerships and seamless integrations with vendors of your choice, including vendors for BI tools, data science technologies, marketing and sales automation software, CRM solutions, and machine learning.</p><p>Another area you might use vendors for is security analytics. Snowflake enables you to connect to existing SIEM software, fraud products, and threat intelligence feeds. Also, Snowflake provides built-in security options from leading BI partners, including Tableau, Looker, Sigma Computing, and Periscope Data, so you can create a wide range of user interfaces, visualizations, and reports that align with your needs, processes, and workflows.</p><h3>17- Additional Features</h3><p><strong>i. Secure Data Sharing</strong></p><p>Let’s put this to the test. In your organization, if you need to pass data to a team in another company in a secure way, how would you do it? Secure FTP? Ugh! An expensive proprietary tool? Blegh! Or — worst of all — an email (hopefully you would at least password-protect it)? Don’t you dare! If any of these are the case, you really need to consider Snowflake Secure Data Sharing.</p><p>Snowflake not only supports view-based data sharing but has enhanced this by revolutionizing how organizations distribute and consume shared data. Unlike FTP and email, Snowflake Data Sharing is far easier to use as it provides instant access to live data and eliminates data copying. The Snowflake Built for the Cloud Architecture enables Data Sharing without any complicated ETL and setup and more importantly allows you to control security in one single place, at the data level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*TM7bg79ZmTUcKUivYifw7Q.png" /></figure><p>With Secure Data Sharing, no actual data is copied or transferred between accounts. All sharing is accomplished through Snowflake’s unique services layer and metadata store. This is an important concept because it means that shared data does not take up any storage in a consumer account and, therefore, does not contribute to the consumer’s monthly data storage charges. The only charges to consumers are for the compute resources (i.e. virtual warehouses) used to query the shared data.</p><p>Real-time secure sharing of data is ready as soon as a data provider adds to or updates data for the end consumers. There are out of the box advantages to this approach such as:</p><p>· Immediate access: no transformation, data movement, loading, or reconstruction is required, and data is available for immediate use.</p><p>· Live data: changes made in real-time by a data provider are immediately available to data consumers without effort. Thus, data is always current.</p><p>· Secure Managed access: a data provider can share all their data to N number of data consumers in a secure, governed manner with minimal effort. The flexibility of controlling all aspects of managed access increases the ease of use.</p><p>· No ETL management: users do not need to manage any ETL for secure data sharing capabilities and operations.</p><p>· Access Logs: Data providers can track and monitor access to Data Shares and quickly respond to the user’s actions.</p><p><strong>ii. Data Marketplace</strong></p><p>A data marketplace is an online transactional location or store that facilitates the buying and selling of data. As many businesses seek to augment or enrich internal data sets with external data, cloud-based data marketplaces are appearing at a growing rate to match data consumers with the right data sellers.</p><p>Snowflake Data Marketplace gives data scientists, business intelligence and analytics professionals, and everyone who desires data-driven decision-making, access to more than 375 live and ready-to-query data sets from more than 125 third-party data providers and data service providers (as of January 29, 2021).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*QkZljGXas_7-vv15uguZNA.png" /></figure><p><strong>USE CASES</strong></p><p>· <strong>Data Augmentation: </strong>Source quality, third-party data to augment your own data sets and make better business decisions.</p><p>· <strong>Data Analysis:</strong> Get personalized data feeds from vendors you already work with or request customized data sets based on your business requirements from the many providers in the Data Marketplace.</p><p>· <strong>Data Science:</strong> Discover new data sets your team can use to train AI/ML models and to improve data science applications.</p><p>· <strong>Data Enrichment:</strong> Take advantage of bidirectional data exchange and enrich your own data by leveraging data enrichment services from different vendors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1eca6127403" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrate Data from Salesforce to Snowflake]]></title>
            <link>https://imharmanbhatia.medium.com/migrate-data-from-salesforce-to-snowflake-dd520f1aed93?source=rss-12e4d7a478d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd520f1aed93</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Harman Bhatia]]></dc:creator>
            <pubDate>Mon, 07 Dec 2020 09:23:54 GMT</pubDate>
            <atom:updated>2020-12-07T09:23:54.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tte-ftZ29tbe1D-lkgKF6A.jpeg" /><figcaption>Ways to migrate data from Salesforce to Snowflake</figcaption></figure><p>If you are reading this, you are probably looking out the ways to transfer data from Salesforce Cloud to Snowflake. In this article, you will get different techniques to extract data from salesforce and load it to Snowflake.</p><h3>What is Salesforce?</h3><p><a href="https://www.salesforce.com/">Salesforce</a>, a cloud-based software-as-a-service platform, is the most popular CRM application in use today. Salesforce is amazingly customizable, has tons of integration functionality, and includes almost too many bells and whistles to count. Companies can use it to do everything from managing account planning to time management and team collaboration.</p><h3>What is Snowflake?</h3><p><a href="https://www.snowflake.net/">Snowflake</a> is a cloud-based data warehouse that’s fast, flexible, and easy to work with. It runs on Amazon Web Services EC2 and S3 instances and separates compute and storage resources, enabling users to scale the two independently and pay only for resources used. Snowflake can natively load and optimize both structured and semi-structured data and make it available via SQL. It provides native support for JSON, Avro, XML, and Parquet data, and can provide access to the same data for multiple workgroups or workloads simultaneously with no contention roadblocks or performance degradation.</p><h3>Extract Data out of Salesforce</h3><p>Salesforce provides many APIs for its products that can deliver data on accounts, leads, tasks, and more. You can find a list of APIs on one of the company’s <a href="https://help.salesforce.com/articleView?id=integrate_what_is_api.htm&amp;type=0"><em>help docs posts</em></a> with some direction on when and how to use each API. By looking through that post, you can get an idea of which API makes the most sense for your use case.</p><p>For our purposes, we’ll use the REST API with <a href="https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/">SOQL</a> (Salesforce Object Query Language), but the same data is available using other protocols, including streaming for real-time receipt of data.</p><h3>Different ways to Migrate data from Salesforce to Snowflake</h3><h4>1. Python Scripts</h4><p>Yes, we can use python scripts to fetch the data from salesforce using<em> </em><a href="https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_what_is_rest_api.htm"><em>REST API</em></a><em>.</em> In Python script, we can connect AWS S3 to load the API’s JSON data directly into AWS S3. We can use various methods to implement this solution such as writing Python Script in the AWS EC2 instance, using Apache Airflow or AWS Lambda for orchestration.</p><p>In my recent project, we got the requirement to migrate the data from Salesforce to Snowflake. At that time, we used the AWS EC2 instance and create the python script inside the instance. In the python script, we used various open-source libraries to connect with AWS S3 and load the data into S3.</p><p>Below are the steps which I followed to load the data from API to S3 -</p><ul><li>Create an AWS EC2 Instance — It is quite easy to create an EC2 instance. You can follow the steps mentioned in <a href="https://docs.aws.amazon.com/efs/latest/ug/gs-step-one-create-ec2-resources.html"><em>AWS EC2 Documentation</em></a><em>. </em>As of now, you can use the default configuration for testing purposes.</li><li>In EC2 instance, Create a Python script, import requests, JSON, and boto3 libraries.</li><li>Write a code to fetch the data using requests.get() method. Connect with AWS S3 using boto3.client() method and load data into S3 using boto3.put_object() method. You can follow<em> </em><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html"><em>boto3 docs</em></a> if required.</li><li>Once data is loaded into AWS S3, you can load the data into Snowflake using AWS S3.</li></ul><h4>2. Apache Airflow</h4><p>Apache Airflow is an open-source workflow management platform. It is basically used for orchestration but there are various open-source Airflow plugins which we can use to extract the data from Salesforce and load it into Snowflake.</p><p>Apache Airflow is a powerful ETL scheduler, organizer, and manager, but it doesn’t process or stream data. For that, you need a plugin like Airflow Plugin — Salesforce to act as a data pipeline. This plugin’s Salesforce Hook authenticates your requests to Salesforce. Then you can create new connections to pull and save Salesforce data. To extract defined datasets, the plugin’s SalesforceToS3Operator operator queries the Salesforce bulk API with Salesforce Object Query Language (SOQL), a version of SQL that talks to the Salesforce datastore.</p><p><a href="https://github.com/airflow-plugins/salesforce_plugin">Airflow Plugin — Salesforce</a> is an<a href="https://blog.panoply.io/top-9-python-etl-tools-and-when-to-use-them"> Apache Airflow</a> plugin developed by Astronomer, Inc. This is an open-source tool in which we can use <a href="https://github.com/airflow-plugins/salesforce_plugin">Salesforce</a> Plugin and <a href="https://github.com/airflow-plugins/snowflake_plugin">Snowflake Plugin</a> to extract the data from Salesforce and load it into Snowflake.</p><p>We can also use the AWS S3 plugin alongside Salesforce to load the data first into AWS S3 and then to Snowflake.</p><h4>3. Sync out for Snowflake — Einstein Analytics</h4><p><a href="https://help.salesforce.com/articleView?id=bi_integrate_connectors_sync_out_snowflake.htm&amp;type=5"><em>Sync Out for Snowflake</em></a> exports your raw local Salesforce data via Tableau CRM to Snowflake using the Tableau CRM output connector for Snowflake. With Sync Out for Snowflake, keep your Salesforce data in Snowflake up to date using scheduled Data Sync without the need for a third-party ETL tool. Fresh Salesforce data is vital if you maintain a central Snowflake data lake for processing, analysis, business automation, or storage. For example, give your shipping logistics team the freshest data by merging your account data from your system of record, Salesforce, with your ERP’s shipping data in your data lake.</p><blockquote><strong>Enable Sync Out</strong></blockquote><ol><li>From Setup, enter Analytics in the Quick Find box.</li><li>Select <strong>Settings</strong> under <strong>Tableau CRM</strong>.</li><li>Select <strong>Enable Snowflake output Connection</strong> and <strong>Save</strong>.</li><li>Turn on and configure the Snowflake output connector as described in <a href="https://help.salesforce.com/articleView?id=bi_integrate_connectors_output_snowflake.htm&amp;type=5">Snowflake Output Connection</a>. The output connection is used to link Tableau CRM to Snowflake. You don’t add or update a Data Prep recipe output node to use Sync Out, as the push happens during Data Sync.</li></ol><h4>4. Data Loader</h4><p>Salesforce’s own ETL product<a href="https://dataloader.io/"> dataloader.io</a> is the company’s supported method for extracting data from Salesforce data stores. If you have a Salesforce account, you can sign in to dataloader.io with the same credentials. But dataloader.io isn’t free with Salesforce. It’s a separate paid service. This cloud data pipeline is powered by the Salesforce Mulesoft Anypoint Platform. It goes beyond what Mulesoft can do as an ETL. dataloader.io can save time by grouping your related objects into a single pull. So you don’t have to export multiple datasets individually and then recombine them in Excel or another database system. The dataloader.io ETL also has connectors to pull data from Box, DropBox, FTP, and SFTP repos into Salesforce.</p><p>dataloader.io has a clean, user-friendly UI with features like search filters and keyboard shortcuts. You can schedule automatic data extractions from Salesforce as frequently as once an hour, but dataloader.io won’t refresh your Salesforce-connected apps and BI tools in real-time.</p><h3>Some of the helpful links —</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqUHQuZjTOFA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqUHQuZjTOFA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqUHQuZjTOFA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0083c45b48d7822ba503ef3264b4abb7/href">https://medium.com/media/0083c45b48d7822ba503ef3264b4abb7/href</a></iframe><ul><li><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">Boto3 1.42.9 documentation</a></li><li><a href="https://docs.aws.amazon.com/AmazonS3/latest/gsg/SigningUpforS3.html">Setting up Amazon S3</a></li></ul><p>There are various other paid tools out there to migrate the data from Salesforce to Snowflake or make a direct connection between Salesforce and Snowflake. If you have a budget then you can go with any paid tool else I recommend using Python scripts with any open source orchestration tool such as Airflow and transfer the data from Salesforce cloud to Snowflake.</p><p>If you have any queries, feel free to comment or mail me at <em>imharmanbhatia@gmail.com.</em></p><h3>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd520f1aed93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just Python Part 6— Functions]]></title>
            <link>https://imharmanbhatia.medium.com/just-python-part-6-functions-417ce44bdfc0?source=rss-12e4d7a478d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/417ce44bdfc0</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Harman Bhatia]]></dc:creator>
            <pubDate>Sun, 29 Mar 2020 07:36:48 GMT</pubDate>
            <atom:updated>2020-03-29T07:41:35.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8i1k6NtVdEM2NUPPEvk-lA.png" /></figure><p>A function is a block of code which only runs when it is called. Python function in any programming language is a sequence of statements in a certain order, given a name. When called, those statements are executed. So we don’t have to write the code again and again for each [type of] data that we want to apply it to. This is called code re-usability.</p><p>We will study the different types of functions in Python: Python built-in functions, Python recursion function, Python lambda function, and Python user-defined functions with their syntax and examples. As you already know, Python gives you many <strong>built-in functions</strong> like print, int, float, bin, hex, string, list, set, dictionary, and so.</p><p>You can also create your own functions. These functions are called <strong><em>user-defined functions</em></strong><em>.</em></p><h4>Syntax of Function</h4><pre>def func_name( parameters ):<br>   &quot;function_docstring&quot;<br>   function_suite<br>   return [expression]</pre><h3>Defining a Function</h3><p>You can define functions to provide the required functionality. Here are simple rules to define a function in Python.</p><ul><li>Function blocks begin with the keyword <strong>def</strong> followed by the function name and parentheses “ ( ) “.</li><li>Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.</li><li>The first statement of a function can be an <strong>optional </strong>statement — the documentation string of the function or <em>docstring</em>.</li><li>The code block within every function starts with a colon (:) and is indented.</li><li>The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.</li></ul><h3>Rules for naming python function (identifier)</h3><p>We follow the same rules when naming a function as we do when naming a variable.</p><ol><li>It can begin with either of the following: A-Z, a-z, and underscore(_).</li><li>The rest of it can contain either of the following: A-Z, a-z, digits(0–9), and underscore(_).</li><li>A reserved keyword may not be chosen as an identifier.</li></ol><p>It is good practice to name a Python function according to what it does.</p><pre>def <strong>hello</strong>():<br>    print(&quot;Hello&quot;)</pre><p>You may use a docstring right under the first line of a function declaration. This is a documentation string, and it explains what the function does.</p><pre>def <strong>func1</strong>():<br>    &quot;&quot;&quot;<br>    This is docstring<br>    &quot;&quot;&quot;<br>    print(&quot;Hello&quot;)</pre><pre>func1.__doc__</pre><p>You can access this docstring using the __doc__ attribute of the function.</p><pre>&gt;&gt; func1.__doc__<br>&#39;\n\tThis is the docstring\n\t&#39;</pre><h4>Calling a Function</h4><p>To call a function, use the function name followed by parenthesis:</p><pre>def my_function():<br>  print(&quot;Hello from a function&quot;)<br><br><strong>my_function()</strong></pre><p>If you don’t yet know what to put in the function, then you should put the pass statement in its body. If you leave its body empty, you get an error “Expected an indented block”. You can even reassign a function by defining it again.</p><pre>&gt;&gt;&gt; def my_function():<br>        pass<br><br><strong>&gt;&gt;&gt; my_function()</strong></pre><h3>Python Function Argument</h3><p>Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.</p><blockquote><em>Arguments</em> are often shortened to <em>args</em> in Python documentations.</blockquote><blockquote><strong>Parameters or Arguments?</strong></blockquote><blockquote>The terms <em>parameter</em> and <em>argument</em> can be used for the same thing: information that are passed into a function.</blockquote><blockquote>From a function’s perspective:</blockquote><blockquote>A parameter is the variable listed inside the parentheses in the function definition.</blockquote><blockquote>An argument is the value that are sent to the function when it is called.</blockquote><p>There are different types of arguments:</p><ol><li>Default argument</li><li>Keyword argument</li><li>Arbitrary argument</li></ol><h4>Default argument</h4><p>A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −</p><pre># Function definition is here<br>def info( name, age = 35 ):<br>   &quot;This prints a passed info into this function&quot;<br>   print(&quot;Name: &quot;, name)<br>   print(&quot;Age &quot;, age)<br>   return;</pre><pre># Now you can call info function<br>info( age=50, name=&quot;miki&quot; )<br>info( name=&quot;miki&quot; )</pre><p>When the above code is executed, it produces the following result −</p><pre>Name:  miki<br>Age  50<br>Name:  miki<br>Age  35</pre><p>Any number of arguments can have a default value. But you must make sure to not have a non-default argument after a default argument. In other words, if you provide a default argument, all others succeeding it must have default values as well. The reason is simple. Imagine you have a function with two parameters. The first argument has a default value, but the second doesn’t. Now when you call it(if it was allowed), you provide only one argument. The interpreter takes it to be the first argument. What happens to the second argument, then? It has no clue.</p><pre>def <strong>sum</strong>(a=1,b):<br>    return a+b</pre><p><strong>SyntaxError: non-default argument follows default argument</strong><br>This was all about the default arguments in Python</p><h4>Keyword Arguments</h4><p>With keyword arguments in python, we can change the order of passing the arguments without any consequences. Let’s take a function to divide two numbers, and return the quotient.</p><pre>def my_function(child3, child2):<br>  print(&quot;The youngest child is &quot; + child3)<br><br>my_function(child2 = &quot;Tobias&quot;, child3 = &quot;Linus&quot;)def my_function(*kids):<br>  print(&quot;The youngest child is &quot; + kids[2])<br><br>my_function(&quot;Emil&quot;, &quot;Tobias&quot;, &quot;Linus&quot;)</pre><blockquote>The phrase <em>Keyword Arguments</em> are often shortened to <em>kwargs</em> in Python documentations.</blockquote><h4>Arbitrary Arguments, *args</h4><p>If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.</p><p>This way the function will receive a <em>tuple</em> of arguments, and can access the items accordingly:</p><pre>def my_function(*kids):<br>  print(&quot;The youngest child is {kids}&quot;)<br><br>my_function(&quot;Emil&quot;, &quot;Tobias&quot;, &quot;Linus&quot;)</pre><h4>Arbitrary Keyword Arguments, **kwargs</h4><p>If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.</p><p>This way the function will receive a <em>dictionary</em> of arguments, and can access the items accordingly:</p><pre>def my_function(**kid):<br>  print(&quot;His last name is &quot; + kid[&quot;lname&quot;])<br><br>my_function(fname = &quot;Tobias&quot;, lname = &quot;Refsnes&quot;)</pre><blockquote><em>Arbitrary Kword Arguments</em> are often shortened to <em>**kwargs</em> in Python documentations.</blockquote><h4>Passing a List as an Argument</h4><p>You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.</p><p>E.g. if you send a List as an argument, it will still be a List when it reaches the function:</p><pre>def my_function(food):<br>  for x in food:<br>    print(x)<br><br>fruits = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br><br>my_function(fruits)</pre><h3>Python return statement</h3><p>A Python function may optionally return a value. This value can be a result that it produced on its execution. Or it can be something you specify- an expression or a value. A return statement with no arguments is the same as return None.</p><pre>def sum( arg1, arg2 ):<br>   # Add both the parameters and return them.&quot;<br>   total = arg1 + arg2<br>   print(&quot;Inside the function : &quot;, total)<br>   return total;<br><br># Now you can call sum function<br>total = sum( 10, 20 );<br>print(&quot;Outside the function : &quot;, total)</pre><p>When the above code is executed, it produces the following result −</p><pre>Inside the function :  30<br>Outside the function :  30</pre><h3>Scope and Lifetime of Variables in Python</h3><p>All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.</p><p>The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python</p><ul><li>Global variables</li><li>Local variables</li></ul><p><strong>Local Scope</strong>- A variable that’s declared inside a function has a local scope. In other words, it is local to that function.</p><pre>def <strong>func3</strong>():<br>    x=7<br>    <strong>print</strong>(x)</pre><pre>&gt;&gt;&gt; <strong>func3</strong>()  #O/P: 7</pre><p>If you then try to access the variable x outside the function, you cannot.</p><pre>&gt;&gt;&gt; x</pre><p>Traceback (most recent call last):</p><p>File “&lt;pyshell#96&gt;”, line 1, in &lt;module&gt;</p><p>x</p><p>NameError: name ‘x’ is not defined</p><p><strong>Global Scope</strong>- When you declare a variable outside python function, or anything else, it has global scope. It means that it is visible everywhere within the program.</p><pre>z = 7<br>def <strong>func3</strong>():<br>    <strong>print</strong>(z)</pre><pre>&gt;&gt;&gt; <strong>func3</strong>()  #O/P: 7</pre><p>However, you can’t change its value from inside a local scope(here, inside a function). To do so, you must declare it global inside the function, using the ‘global’ keyword.</p><pre>&gt;&gt;&gt; def <strong>func4</strong>():<br>        global y<br>        y+=1<br>        <strong>print</strong>(y)</pre><pre>&gt;&gt;&gt; <strong>func4</strong>() #O/P: 8</pre><h4>Lifetime</h4><p>A variable’s lifetime is the period of time for which it resides in the memory.</p><p>A variable that’s declared inside python function is destroyed after the function stops executing. So the next time the function is called, it does not remember the previous value of that variable.</p><pre>&gt;&gt;&gt; def <strong>func1</strong>():<br>        counter=0<br>        counter+=1<br>        <strong>print</strong>(counter)</pre><pre>&gt;&gt;&gt; <strong>func1</strong>() #O/p: 1<br>&gt;&gt;&gt; <strong>func1</strong>() #O/p: 1</pre><p>As you can see here, the function func1() doesn’t print 2 the second time.</p><h3>Deleting Python function</h3><p>Till now, we have seen how to delete a variable. Similarly, you can delete a function with the ‘del’ keyword.</p><pre>&gt;&gt;&gt; del func7<br>&gt;&gt;&gt; <strong>func7</strong>()</pre><h3>Python Lambda Expressions</h3><p>As we said earlier, a function doesn’t need to have a name. A lambda expression in Python allows us to create anonymous python function, and we use the ‘lambda’ keyword for it. The following is the syntax for a lambda expression.</p><p>lambda <em>arguments </em>: <em>expression</em></p><p>It’s worth noting that it can have any number of arguments, but only one expression. It evaluates the value of that expression, and returns the result. Let’s take an example.</p><pre>x = lambda a : a + 10<br>print(x(5))</pre><p>This code takes the numbers 5 as arguments a and put it in the expression (a+10). This makes it 5 + 10 which is 15. Finally, it returns 15.</p><p>Actually, the function object is assigned to the identifier myvar.</p><pre>&gt;&gt;&gt; myvar=lambda a,b:(a*b)+2<br>&gt;&gt;&gt; <strong>myvar</strong>(3,5)</pre><pre>17</pre><p>Lambda functions can take any number of arguments:</p><pre>x = lambda a, b, c : a + b + c<br>print(x(5, 6, 2))</pre><h4>Why Use Lambda Functions?</h4><p>The power of lambda is better shown when you use them as an anonymous function inside another function.</p><p>Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:</p><pre>def myfunc(n):<br>    return lambda a : a * n<br><br>mydoubler = myfunc(2)<br><br>print(mydoubler(11))    #Output: 11 * 2 = 22</pre><p>These functions are called anonymous because they are not declared in the standard manner by using the <em>def</em> keyword. You can use the <em>lambda</em> keyword to create small anonymous functions.</p><ul><li>Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.</li><li>An anonymous function cannot be a direct call to print because lambda requires an expression</li><li>Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.</li></ul><h3>Python Recursion Function</h3><p>In Python function, recursion is when a function calls itself. To see how this could be useful, let’s try calculating the factorial of a number. Mathematically, a number’s factorial is:</p><p>n!=n*n-1*n-2*…*2*1</p><p>To code this, we type the following.</p><pre>def facto(n):<br>  if n==1:<br>    return 1<br>  return n*facto(n-1)<br>  <br>facto(5) #output is 120</pre><p>Try recursive functions using the <em>print</em> statements in between the functions to get the clear understanding how recursive functions work.</p><h3>Conclusion: Python Functions</h3><p>It is important to revise in order to retain information. In this lesson, we learned about the Python function. First, we saw the different types of functions. Now we can create, update, and delete a function. And we know that a function may take arguments and may return a value. We also looked at the scope and lifetime of a variable. Hope you like the Python Function Tutorial.</p><p>Don’t forget to revise the various built-in functions supported by Python. Refer to our tutorials for the same.</p><p><a href="https://medium.com/@harmanbhatia101/just-python-part-4-strings-and-collections-lists-sets-dictionaries-tuples-460797dc540d">Just Python Part 4— Strings and Collections (Lists, Sets, Dictionaries, Tuples)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=417ce44bdfc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just Python Part 5— Statements and Loops]]></title>
            <link>https://medium.com/analytics-vidhya/just-python-part-5-statements-and-loops-6ada70a74ead?source=rss-12e4d7a478d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ada70a74ead</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Harman Bhatia]]></dc:creator>
            <pubDate>Wed, 12 Feb 2020 04:59:03 GMT</pubDate>
            <atom:updated>2020-02-16T13:57:33.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAuwBa_lTlqU0_tjUYcB8g.png" /></figure><p>I believe you are clear with Strings and Collections in Part 4 as they will act as a prerequisite for the statements and loops in which we will use strings, lists, dictionaries and sets. If not, Kindly go through the Strings and Collections.</p><p><a href="https://medium.com/@harmanbhatia101/just-python-part-4-strings-and-collections-lists-sets-dictionaries-tuples-460797dc540d">Just Python Part 4— Strings and Collections (Lists, Sets, Dictionaries, Tuples)</a></p><h3>Python Conditions and If statements</h3><p>Python supports the usual logical conditions from mathematics:</p><ul><li>Equals: a == b</li><li>Not Equals: a != b</li><li>Less than: a &lt; b</li><li>Less than or equal to: a &lt;= b</li><li>Greater than: a &gt; b</li><li>Greater than or equal to: a &gt;= b</li></ul><p>These conditions can be used in several ways, most commonly in “if statements” and loops. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*t1ZVTrHer0jekmSR7B6iqA.jpeg" /></figure><p>An “if statement” is written by using the if keyword.</p><pre>a = 33<br>b = 200<br>if b &gt; a:<br>    print(“b is greater than a”)</pre><h4>Indentation</h4><p>Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.</p><pre>a = 33<br>b = 200<br><strong>if b &gt; a:<br>print(“b is greater than a”) # This will give an error<br></strong>  </pre><h4>Elif</h4><p>The elif keyword is pythons way of saying “if the previous conditions were not true, then try this condition”.</p><pre>a = 33<br>b = 33<br>if b &gt; a:<br>    print(&quot;b is greater than a&quot;)<br>elif a == b:<br>    print(&quot;a and b are equal&quot;)</pre><h3>Else</h3><p>The else keyword catches anything which isn’t caught by the preceding conditions.</p><pre>a = 200<br>b = 33<br>if b &gt; a:<br>    print(&quot;b is greater than a&quot;)<br>elif a == b:<br>    print(&quot;a and b are equal&quot;)<br>else:<br>    print(&quot;a is greater than b&quot;)  </pre><pre>-----------------------------------------------------------------</pre><pre>a = 200<br>b = 33<br>if b &gt; a:<br>    print(&quot;b is greater than a&quot;)<br>else:<br>    print(&quot;b is not greater than a&quot;)  </pre><h4>Short Hand If-else</h4><p>If you have only one statement to execute, you can put it on the same line as the if statement.</p><pre>if a &gt; b: print(&quot;a is greater than b&quot;)  </pre><p>If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:</p><pre>print(&quot;A&quot;) if a &gt; b else print(&quot;B&quot;) </pre><p>You can also have multiple else statements on the same line:</p><pre>print(&quot;A&quot;) if a &gt; b else print(&quot;=&quot;) if a == b else print(&quot;B&quot;)  </pre><h4>Nested If</h4><p>You can have if statements inside if statements, this is called <em>nested</em> if statements.</p><pre>x = 90<br><br>if x &gt; 10:<br>    print(&quot;Above ten,&quot;)<br>    if x &gt; 20:<br>        print(&quot;and also above 20!&quot;)<br>    else:<br>        print(&quot;but not above 20.&quot;)  </pre><h4>And &amp; OR Operators</h4><p>The <strong>and</strong> keyword and <strong>or </strong>keyword are the logical operator, and are used to combine conditional statements:</p><pre>a = 200<br>b = 33<br>c = 500<br>if a &gt; b and c &gt; a:<br>    print(&quot;Both conditions are True&quot;)<br>elif a &gt; b or a &gt; c:<br>    print(&quot;At least one of the conditions is True&quot;)  </pre><h4>The pass Statement</h4><p>if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.</p><pre>a = 33<br>b = 200<br><br>if b &gt; a:<br>    pass</pre><h3>Python For Loops</h3><p>A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).</p><p>This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*QyGknYbGKJNIl60CNox3dw.jpeg" /></figure><h4>Syntax</h4><pre>for iterating_var in sequence:<br>     statements(s)    </pre><p>Print each fruit in a fruit list:</p><pre>fruits = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br>for x in fruits:<br>    print(x)  </pre><h4>The range() Function</h4><p>To loop through a set of code a specified number of times, we can use the range() function,</p><p>The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.</p><pre>for x in range(6):<br>  print(x)</pre><blockquote>Note that range(6) is not the values of 0 to 6, but the values 0 to 5.</blockquote><h4>The break Statement</h4><p>With the break statement we can stop the loop before it has looped through all the items. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The <strong>break</strong> statement can be used in both <em>while</em> and <em>for</em> loops.</p><p>If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*DN6Wqt9HNtSiOFlW_9W60Q.jpeg" /></figure><h4>Syntax</h4><p>The syntax for a <strong>break</strong> statement in Python is as follows −</p><pre>break</pre><p>Exit the loop when x is &quot;banana&quot;:</p><pre>fruits = [“apple”, “banana”, “cherry”]<br>for x in fruits:<br>    print(x)<br>    if x == “banana”:<br>        break</pre><h4>The continue Statement</h4><p>With the continue statement we can stop the current iteration of the loop, and continue with the nextThe <strong>continue</strong> statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.</p><p>The <strong>continue</strong> statement can be used in both <em>while</em> and <em>for</em> loops.</p><h3>Syntax</h3><pre>continue</pre><h4>Flow Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/0*aNI1yJt_En2oUWng.jpg" /></figure><h4><strong>Example</strong></h4><p>Do not print banana:</p><pre>fruits = [“apple”, “banana”, “cherry”]<br>for x in fruits:<br>   if x == “banana”:<br>       continue<br>   print(x)</pre><h4>The pass Statement</h4><p>for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. The <strong>pass</strong> statement is a <em>null</em> operation; nothing happens when it executes. The <strong>pass</strong> is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example) −</p><h4>Syntax</h4><pre>pass</pre><h4>Example</h4><pre>for x in [0, 1, 2]:<br> pass</pre><h3>Using else Statement with Loops</h3><p>Python supports to have an else statement associated with a loop statement</p><ul><li>If the <strong>else</strong> statement is used with a <strong>for</strong> loop, the <strong>else</strong> statement is executed when the loop has exhausted iterating the list.</li><li>If the <strong>else</strong> statement is used with a <strong>while</strong> loop, the <strong>else</strong> statement is executed when the condition becomes false.</li></ul><pre>for x in range(6):<br>  print(x)<br>else:<br>  print(&quot;Finally finished!&quot;)</pre><pre>--------------------------------------------------------------------</pre><pre>for num in range(10,20):     #to iterate between 10 to 20<br>    for i in range(2,num):   #to iterate on the factors of number<br>       if num%i == 0:         #to determine the first factor<br>          j=num/i             #to calculate the second factor<br>          print(&#39;%d equals %d * %d&#39; % (num,i,j))<br>          break #to move to the next number, the #first FOR<br>    else:                  # else part of the loop<br>       print(num, &#39;is a prime number&#39;)</pre><p>When the above code is executed, it produces the following result −</p><pre>10 equals 2 * 5<br>11 is a prime number<br>12 equals 2 * 6<br>13 is a prime number<br>14 equals 2 * 7<br>15 equals 3 * 5<br>16 equals 2 * 8<br>17 is a prime number<br>18 equals 2 * 9<br>19 is a prime number</pre><h3>The while Loop</h3><p>With the while loop we can execute a set of statements as long as a condition is true.</p><h4>Syntax</h4><p>The syntax of a <strong>while</strong> loop in Python programming language is −</p><pre>while expression:<br>   statement(s)</pre><p>Here, <strong>statement(s)</strong> may be a single statement or a block of statements. The <strong>condition</strong> may be any expression, and true is any non-zero value. The loop iterates while the condition is true.</p><p>When the condition becomes false, program control passes to the line immediately following the loop.</p><p>In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.</p><h3>Flow Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/0*7nhVp_JjtRaXNylx.jpg" /></figure><p>Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.</p><h3>Example</h3><pre>i = 1<br>while i &lt; 6:<br>    print(i)<br>    i += 1  </pre><blockquote><strong>Note:</strong> remember to increment i, or else the loop will continue forever.</blockquote><h4>The else Statement</h4><p>With the else statement we can run a block of code once when the condition no longer is true:</p><pre>i = 1<br>while i &lt; 6:<br>    print(i)<br>    i += 1<br>else:<br>    print(&quot;i is no longer less than 6&quot;)</pre><p>The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise else statement gets executed.</p><pre>count = 0<br>while count &lt; 5:<br>   print(count, &quot; is  less than 5&quot;)<br>   count = count + 1<br>else:<br>   print(count, &quot; is not less than 5&quot;)</pre><p>When the above code is executed, it produces the following result −</p><pre>0 is less than 5<br>1 is less than 5<br>2 is less than 5<br>3 is less than 5<br>4 is less than 5<br>5 is not less than 5</pre><h3>Single Statement Suites</h3><p>Similar to the <strong>if</strong> statement syntax, if your <strong>while</strong> clause consists only of a single statement, it may be placed on the same line as the while header.</p><p>Here is the syntax and example of a <strong>one-line while</strong> clause −</p><pre>flag = 1<br>while (flag): print(&#39;Given flag is really true!&#39;)<br>print &quot;Good bye!&quot;</pre><p>It is better not try above example because it goes into infinite loop and you need to press CTRL+C keys to exit.</p><p>This is all about Loops and Statements. If you have any doubt, please drop a comment or visit <a href="http://www.harmanbhatia.com/">www.harmanbhatia.com</a>.</p><p>Exceptional creative achievers apply a mentality of granularity instead of mindset of superficiality. So don’t just read this to complete the topic, practice too.</p><p>Next we will be going through <strong>Python Functions</strong>. Happy Python!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ada70a74ead" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/just-python-part-5-statements-and-loops-6ada70a74ead">Just Python Part 5— Statements and Loops</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just Python Part 4— Strings and Collections (Lists, Sets, Dictionaries, Tuples)]]></title>
            <link>https://imharmanbhatia.medium.com/just-python-part-4-strings-and-collections-lists-sets-dictionaries-tuples-460797dc540d?source=rss-12e4d7a478d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/460797dc540d</guid>
            <dc:creator><![CDATA[Harman Bhatia]]></dc:creator>
            <pubDate>Tue, 04 Feb 2020 05:28:29 GMT</pubDate>
            <atom:updated>2020-02-16T09:53:34.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMd1mln59kY3OYt5wsWImQ.png" /></figure><h3>Python Strings</h3><p>String type is created in python are surrounded by single quotation mark or double quotation mark. Strings can be displayed with the <strong>Print() function </strong>and can be assigned to the variables. For example −</p><pre>&#39;Hello World!&#39; #Creating the string <br>var1 = &quot;Python Programming&quot;   #Assigning the string to variable.</pre><pre>print(&quot;Hello World!&quot;)  #Output - Hello World!<br>print(var1)   #Output - Python Programming</pre><h4>Slicing and Indexing</h4><p>You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.</p><pre>var1 = &quot;Python Programming&quot; </pre><pre>print(var1[2:6]) #Output - &#39;thon&#39;</pre><p>Here the index starts from 0, now 2nd position is at <strong>‘t’ </strong>and 6th position is exclusive so output is <strong>‘thon’.</strong></p><p>Few more examples —</p><pre>var1 = &quot;Python Programming&quot;</pre><pre>print(var1[0]) #Output - &#39;P&#39; </pre><pre>print(var1[0:6]) #Output - &#39;Python&#39;</pre><pre>print(var1[:4]) #Output - &#39;Pyth&#39;</pre><pre>print(var1[7:]) #Output - &#39;Programming&#39;</pre><pre>print(&quot;Updated String :- &quot;, <strong>var1[:6]</strong> + &#39;Strings&#39;)  #Output - &#39;Python Strings&#39;</pre><p>To get the <strong>length </strong>of a string, use the <strong>len()</strong> function.</p><pre>var1 = &quot;Python&quot;</pre><pre><strong>print(len(var1)</strong>) #Output: 6</pre><h4>String Methods</h4><p>Python has a set of built-in methods that you can use on strings.</p><p>Assume string variable <strong>x holds “Hello, Python!”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*IEvS-03tbeWGfHx5dtN_-A.png" /></figure><blockquote>All string methods returns new values. They do not change the original string.</blockquote><p>There are various other methods such as min(), max(), count(), center(), join() etc. If you wish to go through each method, please go to the link mentioned at the end of the tutorial.</p><h4><strong>String Special Operator</strong></h4><p>Assume string variable <strong>a</strong> holds<strong> ‘Hello’</strong> and variable <strong>b</strong> holds<strong> ‘Python’</strong>, then −</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*zS6XogIUDi4He35oUDbPvw.png" /></figure><h4>String Format Operator</h4><p>One of Python’s coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C’s printf() family. Following is a simple example −</p><pre>print(&quot;My name is <strong>%s</strong> and weight is <strong>%d</strong> kg!&quot; % (&#39;Alexa&#39;, 47))</pre><pre>Output - My name is Alexa and weight 47 kg</pre><p>Here is the list of complete set of symbols which can be used along with % −</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*feDEdlx-aTylwKl69rCx1Q.png" /></figure><p>Also, We can use the <strong>format() </strong>method to combine strings and numbers.</p><pre>weight = 47</pre><pre>x = &quot;My name is <strong>{} </strong>and weight is <strong>{} </strong>kg!&quot;</pre><pre>print(x<strong>.format(&#39;Alexa&#39;, weight)</strong>)</pre><pre>Output - My name is Alexa and weight 47 kg</pre><h4>Escape Character</h4><p>To insert characters that are illegal in a string, use an escape character.</p><p>An escape character is a<strong> backslash </strong><strong>\ </strong>followed by the character you want to insert.</p><pre>x = “We are the so-called \”Vikings\” from the north.”</pre><pre>print(x)  </pre><pre>Output - We are the so-called ”Vikings” from the north.</pre><h3>Python Collections</h3><p>There are four collection data types in the Python programming language:</p><ul><li><strong>List</strong> is a collection which is ordered and changeable. Allows duplicate members.</li><li><strong>Tuple</strong> is a collection which is ordered and unchangeable. Allows duplicate members.</li><li><strong>Set</strong> is a collection which is unordered and unindexed. No duplicate members.</li><li><strong>Dictionary</strong> is a collection which is unordered, changeable and indexed. No duplicate members.</li></ul><h3>List</h3><p>A list is a collection which is ordered and changeable. Creating a list is as simple as putting different comma-separated values between square brackets. For example −</p><pre>list1 = [&#39;computer&#39;, &#39;laptop&#39;, 101, 2901]<br>list2 = [1, 2, 3, 4, 5 ]<br>list3 = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]</pre><blockquote>Remember that the first item has index 0.</blockquote><p>Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.</p><p>To get the <strong>length </strong>of a list, use the <strong>len()</strong> function.</p><pre>var1 = [&#39;computer&#39;, &#39;laptop&#39;, 101, 2901]</pre><pre><strong>print(len(var1)</strong>) #Output: 4</pre><h4>Accessing Values in Lists</h4><p>To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −</p><pre>list1 = [&#39;computer&#39;, &#39;laptop&#39;, 101, 2901];<br>list2 = [1, 2, 3, 4, 5 ];</pre><pre>print(&quot;First element of list 1 is &quot;, list1[0])<br>print(&quot;<strong>Slicing </strong>list 2 from 1 to 4 - &quot;, list2[1:4])</pre><pre>First element of list 1 is computer<br>Slicing list 2 from 1 to 4: [2, 3, 4]</pre><h4><strong>Negative Indexing</strong></h4><p>Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.</p><pre>thislist = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br>print(thislist[<strong>-1</strong>])    # Output - &quot;cherry&quot;</pre><pre>thislist = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;, &quot;orange&quot;, &quot;kiwi&quot;, &quot;melon&quot;, &quot;mango&quot;]<br>print(thislist[-4:-1])     #Output - [&#39;orange&#39;, &#39;kiwi&#39;, &#39;melon&#39;]</pre><h4>Update and Delete List Items</h4><p>To add an item to the end of the list, use the <strong>append</strong>() method:</p><pre>thislist = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br>thislist.<strong>append</strong>(&quot;orange&quot;)<br>print(thislist)   #Output - [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;,&quot;orange&quot;]</pre><p>To add an item at the specified index, use the <strong>insert</strong>() method:</p><pre>thislist = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br><strong>thislist.insert(1, &quot;orange&quot;)</strong><br>print(thislist)    #Output - [&quot;apple&quot;, &quot;orange&quot;, &quot;banana&quot;, &quot;cherry&quot;]</pre><p>To change the value of a specific item, refer to the <strong>index </strong>number:</p><pre>thislist = [“apple”, “banana”, “cherry”]<br><strong>thislist[1]</strong> <strong>= “orange”</strong><br>print(thislist)    #Output - [&quot;apple&quot;, &quot;orange&quot;, &quot;cherry&quot;]</pre><p>The remove() method removes the specified item:</p><pre>thislist = [“apple”, “banana”, “cherry”]<br><strong>thislist.remove(“</strong>banana<strong>”)</strong><br>print(thislist)    #Output - [&quot;apple&quot;, &quot;cherry&quot;]</pre><p>The pop() method removes the specified index, (or the last item if index is not specified):</p><pre>thislist = [“apple”, “banana”, “cherry”]<br><strong>thislist.pop()</strong><br>print(thislist)    #Output - [&quot;apple&quot;, &quot;banana&quot;]</pre><p>The del keyword removes the specified index:</p><pre>thislist = [“apple”, “banana”, “cherry”]<br>del thislist[0]<br>print(thislist)  #Output - [“banana”, “cherry”]</pre><p>The del keyword can also delete the list completely:</p><pre>thislist = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br><strong>del thislist</strong><br>print(thislist) #this will cause an error because you have succsesfully deleted &quot;thislist&quot;.</pre><p>The clear() method empties the list:</p><pre>thislist = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br>thislist.<strong>clear()</strong><br>print(thislist)  #[]</pre><h4>Copy a List</h4><p>You cannot copy a list simply by typing list2 = list1, because: list2 will only be a <em>reference</em> to list1, and changes made in list1 will automatically also be made in list2.</p><p>There are ways to make a copy, one way is to use the built-in List method copy().</p><p>Make a copy of a list with the copy() method:</p><pre>thislist = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br>mylist = thislist.<strong>copy()</strong><br>print(mylist)    #[&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]</pre><p>Another way to make a copy is to use the built-in method list().</p><pre>thislist = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br>mylist = list(thislist)<br>print(mylist)    #[&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]</pre><h4>Join Two Lists</h4><p>There are several ways to join, or concatenate, two or more lists in Python.</p><p>Join two list:</p><pre>list1 = [&quot;a&quot;, &quot;b&quot; , &quot;c&quot;]<br>list2 = [1, 2, 3]<br><br>list3 = list1 <strong>+</strong> list2<br>print(list3)    # Output -  [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, 1, 2, 3]</pre><p>Append list2 into list1:</p><pre>list1 = [&quot;a&quot;, &quot;b&quot; , &quot;c&quot;]<br>list2 = [1, 2, 3]<br><br>for x in list2:<br>  <strong>list1.append(x)</strong><br><br>print(list1)    # Output -  [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, 1, 2, 3]</pre><p>Use the extend() method to add list2 at the end of list1:</p><pre>list1 = [&quot;a&quot;, &quot;b&quot; , &quot;c&quot;]<br>list2 = [1, 2, 3]<br><br><strong>list1.extend(list2)</strong><br>print(list1)    # Output -  [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, 1, 2, 3]</pre><h4>List Methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*HdvI6NFh8beNhs-XTT-0DQ.png" /></figure><h3>Tuples</h3><p>A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.</p><pre>tup1 = (&#39;computer&#39;, &#39;laptop&#39;, 101, 2901)<br>tup2 = (1, 2, 3, 4, 5 )<br>tup3 = (&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;)</pre><blockquote>Remember that the first item has index 0.</blockquote><p>Similar to list indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.</p><p>To get the <strong>length </strong>of a tuple, use the <strong>len()</strong> function.</p><pre>var1 = (&#39;computer&#39;, &#39;laptop&#39;, 101, 2901)</pre><pre><strong>print(len(var1)</strong>) #Output: 4</pre><h4>Accessing Values in Tuples</h4><p>To access values in tuples, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −</p><pre>tup1 = (&#39;computer&#39;, &#39;laptop&#39;, 101, 2901)<br>tup2 = (1, 2, 3, 4, 5)</pre><pre>print(&quot;First element of tup1 is &quot;, tup1[0])<br>print(&quot;<strong>Slicing </strong>tup2 from 1 to 4 - &quot;, tup2[1:4])</pre><pre>First element of tup1 is computer<br>Slicing tup2 from 1 to 4: (2, 3, 4)</pre><h4>Negative Indexing</h4><p>Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.</p><pre>tup1 = (&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;)<br>print(tup1[<strong>-1</strong>])    # Output - &quot;cherry&quot;</pre><pre>tup2= (&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;, &quot;orange&quot;, &quot;kiwi&quot;, &quot;melon&quot;, &quot;mango&quot;)<br>print(tup2[-4:-1])     #Output - (&#39;orange&#39;, &#39;kiwi&#39;, &#39;melon&#39;)</pre><h4>Add Items</h4><p>Once a tuple is created, you cannot add items to it. Tuples are <strong>unchangeable</strong>.</p><pre>thistuple = (&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;)<br>thistuple[3] = &quot;orange&quot; # This will raise an error<br>print(thistuple)  </pre><h4>Create Tuple With One Item</h4><p>To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple.</p><pre>thistuple = (&quot;apple&quot;,)<br>print(type(thistuple))    #type tuple<br><br>#NOT a tuple<br>thistuple = (&quot;apple&quot;)<br>print(type(thistuple))    # type str</pre><h4>Remove Items</h4><p><strong>Note:</strong> You cannot remove items in a tuple.</p><p>Tuples are <strong>unchangeable</strong>, so you cannot remove items from it, but you can delete the tuple completely:</p><p>The del keyword can delete the tuple completely:</p><pre>thistuple = (“apple”, “banana”, “cherry”)<br>del thistuple<br>print(thistuple) #this will raise an error because the tuple no longer exists  </pre><h4>Join Two Tuples</h4><p>To join two or more tuples you can use the + operator:</p><pre>tuple1 = (&quot;a&quot;, &quot;b&quot; , &quot;c&quot;)<br>tuple2 = (1, 2, 3)<br><br>tuple3 = tuple1 + tuple2<br>print(tuple3)   # Output - (&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, 1, 2, 3)  </pre><h3>Python Sets</h3><p>A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.</p><pre>thisset = {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;}<br>print(thisset)    #  {&#39;cherry&#39;, &#39;apple&#39;, &#39;banana&#39;}  </pre><blockquote><strong>Note:</strong> Sets are unordered, so you cannot be sure in which order the items will appear.</blockquote><h4>Access Items</h4><p>You cannot access items in a set by referring to an index, since sets are unordered the items has no index.</p><p>But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.</p><pre>thisset = {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;}<br><br>for x in thisset:<br>  print(x)     # prints each element</pre><pre>thisset = {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;}<br><br>print(&quot;banana&quot; in thisset)  #  True  </pre><p>To determine how many items a set has, use the len() method:</p><pre>var1 = {&#39;computer&#39;, &#39;laptop&#39;, 101, 2901}</pre><pre><strong>print(len(var1)</strong>) #Output: 4</pre><h4>Change Items</h4><p>Once a set is created, you cannot change its items, but you can add new items.</p><h4>Add Items</h4><p>To add one item to a set use the add() method.</p><p>To add more than one item to a set use the update() method.</p><pre>set1= {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;}<br><br>set1.add(&quot;orange&quot;)<br><br>print(set1)   #{&quot;apple&quot;, &quot;orange&quot;, &quot;banana&quot;, &quot;cherry&quot;}</pre><pre>set1.update([&quot;orange&quot;, &quot;mango&quot;])<br><br>print(set1)    #{&quot;apple&quot;, &quot;orange&quot;, &quot;banana&quot;,&quot;mango&quot;, &quot;cherry&quot;}</pre><h3>Remove Item</h3><p>To remove an item in a set, use the remove(), or the discard() method.</p><pre>rm_set = {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;}<br><br>rm_set.remove(&quot;banana&quot;)<br><br>print(rm_set)    # Output: {&quot;apple&quot;, &quot;cherry&quot;}</pre><blockquote><strong>Note:</strong> If the item to remove does not exist, remove() will raise an error.</blockquote><p>Remove “banana” by using the discard() method:</p><pre>rm_set = {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;}<br><br>rm_set.discard(&quot;banana&quot;)<br><br>print(rm_set)   # Output: {&quot;apple&quot;, &quot;cherry&quot;}  </pre><blockquote><strong>Note:</strong> If the item to remove does not exist, discard() will <strong>NOT</strong> raise an error.</blockquote><p>Remove the last item by using the pop() method:</p><pre>rm_set = {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;}<br><br>x = rm_set.pop()<br><br>print(x)   # Output: apple<br><br>print(rm_set)   #Output: {&#39;cherry&#39;, &#39;banana&#39;}  </pre><blockquote><strong>Note:</strong> Sets are <em>unordered</em>, so when using the pop() method, you will not know which item that gets removed.</blockquote><p>The clear() method empties the set:</p><pre>rm_set = {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;}<br><br>rm_set.clear()  <br><br>print(rm_set)   #set()</pre><p>The del keyword will delete the set completely:</p><pre>rm_set = {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;}<br><br>del rm_set<br><br>print(rm_set)   #this will raise an error because the set no longer exists  </pre><h4>Join Two Sets</h4><p>There are several ways to join two or more sets in Python.</p><p>You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:</p><p>The union() method returns a new set with all items from both sets:</p><pre>set1 = {&quot;a&quot;, &quot;b&quot; , &quot;c&quot;}<br>set2 = {1, 2, 3}<br><br>set3 = set1.union(set2)<br>print(set3)  </pre><p>The update() method inserts the items in set2 into set1:</p><pre>set1 = {&quot;a&quot;, &quot;b&quot; , &quot;c&quot;}<br>set2 = {1, 2, 3}<br><br>set1.update(set2)<br>print(set1)</pre><blockquote><strong>Note:</strong> Both union() and update() will exclude any duplicate items.</blockquote><h4>Set Methods</h4><p>Python has a set of built-in methods that you can use on sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Z2auyd46MH_u6xhnZ-kCNA.png" /></figure><h3>Python Dictionaries</h3><p>A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.</p><p>Create and print a dictionary:</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>print(dict)  #This will print the dictionary</pre><p>To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>print(dict[&#39;Age&#39;])   #Output: 7<br>print(dict[&#39;Name&#39;])   #Output: Zara</pre><p>There is also a method called get() that will give you the same result:</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>print(dict.get(&#39;Age&#39;))   #Output: 7  </pre><p>To determine how many items (key-value pairs) a dictionary has, use the len() method.</p><pre>print(len(thisdict))</pre><h4>Updating Dictionary</h4><p>You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>dict[&#39;Age&#39;] = 8; # update existing entry<br>dict[&#39;School&#39;] = &quot;DPS School&quot;; # Add new entry</pre><pre>print(dict[&#39;Age&#39;])  #Output: 8<br>print(dict[&#39;School&#39;])    #Output: DPS School</pre><h4>Removing Items</h4><p>There are several methods to remove items from a dictionary:</p><p>The pop() method removes the item with the specified key name:</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>dict.pop(&#39;Class&#39;)<br>print(dict)   #Output: {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7}</pre><p>The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>dict.popitem()<br>print(dict)   #Output: {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7}</pre><p>The del keyword removes the item with the specified key name:</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>del dict[&#39;Class&#39;]<br>print(dict)   #Output: {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7}  </pre><p>The del keyword can also delete the dictionary completely:</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>del dict<br>print(dict) #this will cause an error because &quot;dict&quot; no longer exists.</pre><p>The clear() keyword empties the dictionary:</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>dict.clear()<br>print(dict)</pre><h4>Copy a Dictionary</h4><p>You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a <em>reference</em> to dict1, and changes made in dict1 will automatically also be made in dict2.</p><p>Make a copy of a dictionary with the copy() method:</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>cdict = dict.copy()<br>print(cdict)  # It will be the copy of dict</pre><p>Another way to make a copy is to use the built-in method dict().</p><pre>dict = {&#39;Name&#39;: &#39;Zara&#39;, &#39;Age&#39;: 7, &#39;Class&#39;: &#39;First&#39;}<br>cdict = dict(dict)<br>print(cdict)  # It will be the copy of dict</pre><h3>Dictionary Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*T-R_bQ8yfILh2md58S3CGw.png" /></figure><p>So this is all about the Strings and Collections i.e. Lists, Tuples, Sets and Dictionaries in python. Below are few links which will be helpful to you.</p><ul><li><a href="https://www.geeksforgeeks.org/python-list/">Python Lists - GeeksforGeeks</a></li><li><a href="https://data-flair.training/blogs/python-list-examples/">Python List with Examples - A Complete Python List Tutorial - DataFlair</a></li></ul><p>Nothing works until you work so practice more, solve as many different types of problems as you can. Next we will be moving to the <strong>Python Loops and Conditions.</strong></p><p><a href="https://medium.com/@harmanbhatia101/just-python-part-5-statements-and-loops-6ada70a74ead">Just Python Part 5— Statements and Loops</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=460797dc540d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just Python Part 3 — Variables and Types]]></title>
            <link>https://medium.com/analytics-vidhya/just-python-part-3-variables-and-types-385762b8cfd5?source=rss-12e4d7a478d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/385762b8cfd5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Harman Bhatia]]></dc:creator>
            <pubDate>Fri, 31 Jan 2020 05:08:54 GMT</pubDate>
            <atom:updated>2020-02-16T09:51:50.233Z</atom:updated>
            <content:encoded><![CDATA[<h3>Just Python Part 3 — Variables, Operators and Types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Mkq-bpg_rbSLz71iLiy6g.png" /></figure><p>In this tutorial, we will be learning the python variables, different types of operators and data types. I believe you have gone through the basics of python, if not please go through the below part to have a better clarity and understanding of Part 3.</p><p><a href="https://medium.com/analytics-vidhya/just-python-part-2-basics-f59de90c9eef">Just Python Part 2 — Basics</a></p><h3>Creating Variables</h3><p>Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.</p><p>Unlike other programming languages, Python has no command for declaring a variable. The declaration happens automatically when you assign a value to a variable. The <em>equal </em>sign (=) is used to assign values to variables.</p><pre><strong>counter = 100</strong>          # An integer assignment<br><strong>miles   = 1000.0</strong>       # A floating point<br><strong>name    = &quot;John&quot; </strong>      # A string<br><br>print counter<br>print miles<br>print name</pre><p>Here, 100, 1000.0 and “John” are the values assigned to <em>counter</em>, <em>miles</em>, and <em>name</em> variables, respectively. This produces the following result −</p><pre><strong>100<br>1000.0<br>John</strong></pre><h3>Variable Names</h3><p>A variable can have a short name (like x and y) or a more descriptive name (name,counter, miles). Rules for Python variables:</p><ul><li>A variable name must start with a letter or the underscore character</li><li>A variable name cannot start with a number</li><li>A variable name can only contain alpha-numeric characters and underscores (A-z, 0–9, and _ )</li><li>Variable names are case-sensitive (age, Age and AGE are three different variables)</li></ul><blockquote>Remember that variable names are case-sensitive</blockquote><h3>Reserved Words</h3><p>The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.</p><figure><img alt="Reserved Words" src="https://cdn-images-1.medium.com/max/394/1*OtQhLeD6ShV_0T8FeoDCqw.png" /></figure><h3>Multiple Assignment of Variables</h3><p>Python allows you to assign single value to multiple variables.</p><pre>a = b = c = 1</pre><p>You can also assign multiple value to multiple variables.</p><pre>a,b,c = 1,2,&quot;john&quot;</pre><h3>Output Variables</h3><p>There are different ways to use variable. Python print statement is used to output variables. Operator <em>“+”</em> is used for adding one variable to another.</p><pre>str1 = &#39;Hello&#39;<br>print(str)          # Prints string - Hello</pre><pre>str2 = &#39;World!&#39; <br>print(str1 + &quot; &quot; + str2)    #Prints string - Hello World! </pre><h3>Global Variables</h3><p>Variables that are created outside of a function (as in all of the examples above) are known as global variables.</p><p>Global variables can be used by everyone, both inside of functions and outside.</p><pre>x = &quot;Love&quot;</pre><pre>def myfunc():<br> print(&quot;Python is &quot;+ x)</pre><pre>myfunc() #Prints Python is Love</pre><p>If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.</p><pre>x = &quot;Love&quot;</pre><pre>def myfunc():<br>    <strong>x = &quot;Awesome&quot;</strong><br>    print(&quot;Python is &quot;+ x)</pre><pre>myfunc() #Prints Python is Awesome</pre><pre>print(&quot;Python is &quot; + x) #Prints Python is Love</pre><h4>The global Keyword</h4><p>Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.</p><p>To create a global variable inside a function, you can use the global keyword.</p><pre>x = &quot;Love&quot;</pre><pre>def myfunc():<br>    <strong>global x</strong><br>    <strong>x = &quot;Awesome&quot;</strong></pre><pre>myfunc() </pre><pre>print(&quot;Python is &quot; + x) #Prints <strong>Python is Awesome</strong></pre><h3>Python Data Types</h3><p>Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.</p><h4>Built-in Data types</h4><p>Python has the following data types built-in by default, in these categories:</p><p>Text Type: str</p><p>Numeric Types:int, float, complex</p><p>Sequence Types:list, tuple, range</p><p>Mapping Type:dict</p><p>Set Types:set, frozenset</p><p>Boolean Type:bool</p><p>Binary Types:bytes, bytearray, memoryview</p><h4>Getting the Data Type</h4><p>You can get the data type of any object by using the type() function:</p><pre>x = 5<br>print(type(x)) #Print &lt;class &#39;int&#39;&gt;</pre><pre>y = &quot;Alex&quot;<br>print(type(y)) #Print &lt;class &#39;str&#39;&gt;</pre><h3>Python Operators</h3><p>Operators are used to perform operations on variables and values.</p><p>Python divides the operators in the following groups:</p><ul><li>Arithmetic operators</li><li>Assignment operators</li><li>Comparison operators</li><li>Logical operators</li><li>Identity operators</li><li>Membership operators</li><li>Bitwise operators</li></ul><p><strong>Arithmetic operators</strong></p><p>Assume variable a holds value 10 and variable b holds 20 in the below examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*yk0ssB5-xK59emFxf9gxCg.png" /></figure><p><strong>Assignment operators</strong></p><p>Assume variable a holds value 10 and variable b holds 20 in the below examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*WLdhNeZkK6p7dCyOzRI6ug.png" /></figure><p><strong>Comparison operators</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*tIC7r938Pjn_cPMaRZPkFA.png" /></figure><p><strong>Logical operators</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*0rsp0CtjWwFeAWLj0WuZww.png" /></figure><p><strong>Identity operators</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*WYnChhL4b7FMlo3DFYURSg.png" /></figure><p><strong>Membership operators</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*rwD1M8R2sFqO45ROxO04nw.png" /></figure><p><strong>Bitwise operators</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*yTEwNP-DsvrU0V-RMP3a_w.png" /></figure><p>This is all about python variables, data types and operators. In the next tutorial, we will be heading towards<strong> Python Collections i.e. Strings, Lists, Dictionaries and Tuples.</strong></p><blockquote>Elite producers and everyday heroes understand that what you do each day matters far more than what you do once a while. So <strong>Practice Daily</strong> to be a <strong>Victor</strong>.</blockquote><p><a href="https://medium.com/@harmanbhatia101/just-python-part-4-strings-and-collections-lists-sets-dictionaries-tuples-460797dc540d">Just Python Part 4— Strings and Collections (Lists, Sets, Dictionaries, Tuples)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=385762b8cfd5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/just-python-part-3-variables-and-types-385762b8cfd5">Just Python Part 3 — Variables and Types</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>