Debbie Clay

Debbie Clay


Create and deploy Python source code to Azure Functions

The Azure Functions extension for VS Code greatly simplifies the process of using Functions by automatically handling many configuration concerns.

If you encounter any problems in the course of this tutorial, feel free to file an issue in the Visual Studio Code documentation repository.


Details for each of these are in the sections that follow:

Azure subscription

If you don’t have an Azure subscription, sign up now for a free 30-day account with $200 in Azure credits to try out any combination of services.

Visual Studio Code, Python, and the Azure Functions extension

Install the following software:

Azure Functions Core Tools

Follow the instructions for your operating system on Work with Azure Functions Core Tools in the Azure documentation. (The tools themselves are written in .NET Core, and the Core Tools package is best installed using the Node.js package manager, npm, which is why you need to install .NET Core and Node.js at present, even for Python code. Fortunately, you need install these components only once, after which VS Code automatically prompts you to install any updates.)

Sign in to Azure

Once the Functions extension is installed, sign into your Azure account by navigating to the Azure: Functions explorer, select Sign in to Azure, and follow the prompts.

After signing in, verify that you see the email account of your Azure subscription in the Status Bar:

The name you’ve assigned to your subscription also appears in the Azure: Functions explorer (“Primary” in the image below):

Note: If you see the error “Cannot find subscription with name [subscription ID]”, this may be because you are behind a proxy and unable to reach the Azure API. Configure HTTP_PROXY and HTTPS_PROXY environment variables with your proxy information in your terminal:

# macOS/Linux
export HTTPS_PROXY=https://username:password@proxy:8080
export HTTP_PROXY=http://username:password@proxy:8080

set HTTPS_PROXY=https://username:password@proxy:8080
set HTTP_PROXY=http://username:password@proxy:8080

Verify prerequisites

To verify that all the Azure Functions tools are installed, select the Terminal: Create New Integrated Terminal command from the Command Palette (Ctrl+Shift+P), then run the command func:

The output that starts with the Azure Functions logo (you need to scroll the output upwards) indicates that the Azure Functions Core Tools are present.

Create the Function

  1. Code for Azure Functions is managed within a Function “project,” which you create first before creating the code. In Azure: Functions explorer (opened using the Azure icon on the left side), select the New Project command icon, or open the Command Palette and select Azure Functions: Create New Project.
  2. In the prompts that follow:
  • Specify a folder for the project. (The default is the current folder open in VS Code and you may want to create a subfolder separately.)
  • Select Python for the language.
  • Select HTTP trigger for the template. A function that uses an HTTP trigger is run whenever there’s an HTTP request made to the function’s endpoint. (You can see that there are a variety of other triggers for Azure Functions. To learn more, see What can I do with Functions? in the Azure documentation.)
  • Name your function “HttpExample” (rather than accepting the default “HTTPTrigger”) to distinguish the function itself from the trigger. This name is used for a subfolder that contains the function’s code along with configuration data, and also defines the name of the HTTP endpoint.
  • Select Anonymous for the authorization level, which makes the function publicly accessible to anyone.
  • If prompted with “Select how you would like to open your project,” select Open in current window.
  1. After a short time, you see a message that the new project was created. In the Explorer, you see the subfolder created for the function, and VS Code opens the file that contains the default function code:

Note If VS Code tells you that you don’t have a Python interpreter selected when it opens, use the Python: Select Interpreter command from the Command Palette and select the virtual environment in the local .env folder (which was created as part of the project).

Tip: Whenever you want to create another function in the same project, use the Create Function command in the Azure: Functions explorer, or use the Azure Functions: Create Function command from the Command Palette (Ctrl+Shift+P). Both commands prompt you for a function name (which is the name of the endpoint), then creates a subfolder with the default files.

Examine the code files

In the newly created function subfolder, you see three files: contains the function’s code, function.json describes the function to Azure Functions, and sample.dat is a sample data file. You can delete sample.dat if you want, as it exists only to show that you can add other files to the subfolder.

Let’s look at function.json first, then the code in


The function.json file provides the necessary configuration information for the Azure Functions endpoint:

  "scriptFile": "\_\_init\_\",
  "bindings": \[
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": \[
      "type": "http",
      "direction": "out",
      "name": "$return"

You can see that scriptFile identifies the startup file for the code, which must contain a Python function named main. You can factor your code into multiple files so long as the file specified here contains a main function.

The bindings element contains two objects, one to describe incoming requests, and the other to describe the HTTP response. For incoming requests ("direction": "in"), the function responds to HTTP GET or POST requests and doesn’t require authentication. The response ("direction": "out") is an HTTP response that returns whatever value is returned from the main Python function.


When you create a new function, Azure Functions provides default Python code in

import logging

import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:‘Python HTTP trigger function processed a request.’)

name = req.params.get('name')
if not name:
        req\_body = req.get\_json()
    except ValueError:
        name = req\_body.get('name')

if name:
    return func.HttpResponse(f"Hello {name}!")
    return func.HttpResponse(
         "Please pass a name on the query string or in the request body",

The important parts of the code are as follows:

  • You must import func from azure.functions; importing the logging module is optional but recommended.
  • The required main Python function receives a func.request object named req, and returns a value of type func.HttpResponse. You can learn more about the capabilities of these objects in the func.HttpRequest and func.HttpResponse references.
  • The body of main then processes the request and generates a response. In this case, the code looks for a name parameter in the URL. Failing that, it checks if the request body contains JSON (using func.HttpRequest.get_json) and that the JSON contains a name value (using the get method of the JSON object returned by get_json).
  • If a name is found, the code returns the string “Hello” with the name appended; otherwise it returns an error message.

Test and debug locally

  1. When you create the Functions project, the VS Code extension also creates a launch configuration in .vscode/launch.json that contains a single configuration named Attach to Python Functions. This configuration means you can just press F5 or use the Debug explorer to start the project:
  2. When you start the debugger, a terminal opens showing output from Azure Functions, including a summary of the available endpoints (your URL might be different if you used a name other than “HttpExample”):

Hosting environment: Production
Content root path: d:\Examples\Python\AzureFunctions
Now listening on:
Application started. Press Ctrl+C to shut down.

Http Functions:

    HttpExample: \[GET,POST\] http://localhost:7071/api/HttpExample
  1. Use Ctrl+click (Cmd+click on macOS) on the URL in the VS Code Output window to open a browser to that address, or start a browser and paste in the same URL. In either case, you can see that the endpoint is api/<function_name>, in this case api/HttpExample. However, because that URL doesn’t include a name parameter, the browser window should just show, “Please pass a name on the query string or in the request body” as appropriate for that path in the code.
  2. Now try adding a name parameter to the use, such as [http://localhost:7071/api/HttpExample?name=VS%20Code](http://localhost:7071/api/HttpExample?name=VS%20Code), and in the browser window you should see the message, “Hello VS Code!”, demonstrating that you’ve run that code path.
  3. To pass the name value in a JSON request body, you can use a tool like curl with the JSON inline:

# Mac OS/Linux: modify the URL if you’re using a different function name
curl --header “Content-Type: application/json” --request POST \
–data {“name”:“VS Code”} http://localhost:7071/api/HttpExample

Windows (escaping on the quotes is necessary; also modify the URL

if you’re using a different function name)

curl --header “Content-Type: application/json” --request POST \
–data {“”“name”“”:“”“VS Code”“”} http://localhost:7071/api/HttpExample

  1. Alternately, create a file like data.json that contains {"name":"VS Code"} and use the command curl --header "Content-Type: application/json" --request POST --data @data.json [http://localhost:7071/api/HttpExample](http://localhost:7071/api/HttpExample).
  2. To test debugging the function, set a breakpoint on the line that reads name = req.params.get('name') and make a request to the URL again. The VS Code debugger should stop on that line, allowing you to examine variables and step through the code. (For a short walkthrough of basic debugging, see Tutorial - Configure and run the debugger.)
  3. When you’re satisfied that you’ve thoroughly tested the function locally, stop the debugger (with the Debug > Stop Debugging menu command or the Disconnect command on the debugging toolbar).

Deploy to Azure Functions

In these steps, you use the Functions extension to create a “Function App” on Azure. A Function App is composed of a storage account for data, an App Service Plan (which corresponds to the Linux virtual machine on which the App Service runs), and an App Service (the hosting service for your endpoints that runs on the virtual machine). All of these resources are organized within a single resource group.

  1. In the Azure: Functions explorer, select the Deploy to Function App command, or use the Azure Functions: Deploy to Function App command on the Command Palette. A “Function App” here is again the Azure resource that hosts your code.
  2. When prompted, select Create New Function App in Azure, and provide a name that’s unique across Azure (typically using your personal or company name along with other unique identifiers; you can use letters, numbers, and hyphens). If you previously created a Function App, its name appears in this list of options.
  3. The extension performs the following actions, which you can observe in VS Code popup messages and the Output window (the process takes a few minutes):
  • Create a resource group using the name you gave (removing hyphens).
  • In that resource group, create the storage account, App Service Plan, and App Service to host your code.
  • Deploy your code to the Function app.
  1. You can also see progress in the Azure: Functions explorer:
  2. Once deployment is complete, the Output window shows the public endpoint on Azure:

HTTP Trigger Urls:

  1. Use this endpoint to run the same tests you did locally, using URL parameters and/or requests with JSON data in the request body. You should see the same results from the public endpoint as you did locally.

Add a second Function

After your first deployment, you can make changes to your code, such as adding additional functions, and redeploy to the same Functions App.

  1. In the Azure: Functions explorer, select the Create Function command or use Azure Functions: Create Function from the Command Palette. Specify the following details for the function:
  • Template: HTTP trigger
  • Name: “DigitsOfPi”
  • Authorization level: Anonymous
  1. In the VS Code file explorer, you should see a subfolder for your function name that again contains files named, function.json, and sample.dat.
  2. Replace the code in to match the following, which generates a string containing the value of PI to a number of digits specified in the URL (this code uses only a URL parameter)

import logging

import azure.functions as func

“”" Adapted from the second, shorter solution at

def pi_digits_Python(digits):
scale = 10000
maxarr = int((digits / 4) * 14)
arrinit = 2000
carry = 0
arr = [arrinit] * (maxarr + 1)
output = “”

for i in range(maxarr, 1, -14):
    total = 0
    for j in range(i, 0, -1):
        total = (total \* j) + (scale \* arr\[j\])
        arr\[j\] = total % ((j \* 2) - 1)
        total = total / ((j \* 2) - 1)

    output += "%04d" % (carry + (total / scale))
    carry = total % scale

return output;

def main(req: func.HttpRequest) -> func.HttpResponse:‘DigitsOfPi HTTP trigger function processed a request.’)

digits\_param = req.params.get('digits')

if digits\_param is not None:
        digits = int(digits\_param)
    except ValueError:
        digits = 10   # A default

    if digits > 0:
        digit\_string = pi\_digits\_Python(digits)

        # Insert a decimal point in the return value
        return func.HttpResponse(digit\_string\[:1\] + '.' + digit\_string\[1:\])

return func.HttpResponse(
     "Please pass the URL parameter ?digits= to specify a positive number of digits.",
  1. Because the code supports only HTTP GET, modify function.json so that the "methods" collection contains only "get" (that is, remove "post"). The whole file should appear as follows:

“scriptFile”: “”,
“bindings”: [
“authLevel”: “anonymous”,
“type”: “httpTrigger”,
“direction”: “in”,
“name”: “req”,
“methods”: [
“type”: “http”,
“direction”: “out”,
“name”: “$return”

  1. Start the debugger by pressing F5 or selecting the Debug > Start Debugging menu command. The Output window should now show both endpoints in your project:

Http Functions:

    DigitsOfPi: \[GET\] http://localhost:7071/api/DigitsOfPi

    HttpExample: \[GET,POST\] http://localhost:7071/api/HttpExample
  1. In a browser, or from curl, make a request to [http://localhost:7071/api/DigitsOfPi?digits=125](http://localhost:7071/api/DigitsOfPi?digits=125) and observe the output. (You might notice that the code algorithm isn’t entirely accurate, but we’ll leave the improvements to you!) Stop the debugger when you’re finished.
  2. Redeploy the code by using the Deploy to Function App in the Azure: Functions explorer. If prompted, select the Function App created previously.
  3. Once deployment finishes (it takes a few minutes!), the Output window shows the public endpoints with which you can repeat your tests.

Clean up resources

The Function App you created includes resources that can incur minimal costs (refer to Functions Pricing). To clean up the resources, right-click the Function App in the Azure: Functions explorer and select Delete Function App. You can also visit the Azure portal, select Resource groups from the left-side navigation pane, select the resource group that was created in the process of this tutorial, and then use the Delete resource group command.

Next steps

Congratulations on completing this walkthrough of deploying Python code to Azure Functions! You’re now ready to create many more serverless functions.

As noted earlier, you can learn more about the Functions extension by visiting its GitHub repository, vscode-azurefunctions. Issues and contributions are also welcome.

To learn more about Azure Functions, browse the Azure Functions documentation, and especially explore the different triggers you can use.

To learn more about Azure services that you can use from Python, including data storage along with AI and Machine Learning services, visit Azure Python Developer Center.

There are also other Azure extensions for VS Code that you may find helpful. Just search on “Azure” in the Extensions explorer:

Some popular extensions are:

And again, if you encountered any problems in the course of this tutorial, feel free to file an issue in the VS Code docs repo.

#python #azure

What is GEEK

Buddha Community

Create and deploy Python source code to Azure Functions
Easter  Deckow

Easter Deckow


PyTumblr: A Python Tumblr API v2 Client



Install via pip:

$ pip install pytumblr

Install from source:

$ git clone
$ cd pytumblr
$ python install


Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(
) # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in tool (if you already have a consumer key & secret)
  2. The Tumblr API console at
  3. Get sample login code at

Supported Methods

User Methods # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('') # follow a blog
client.unfollow('') # unfollow a blog, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python test

Author: tumblr
Source Code:
License: Apache-2.0 license

#python #api 

Ray  Patel

Ray Patel


Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Tamale  Moses

Tamale Moses


Exploring Mutable and Immutable in Python

In this Python article, let's learn about Mutable and Immutable in Python. 

Mutable and Immutable in Python

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.

Both of these states are integral to Python data structure. If you want to become more knowledgeable in the entire Python Data Structure, take this free course which covers multiple data structures in Python including tuple data structure which is immutable. You will also receive a certificate on completion which is sure to add value to your portfolio.

Mutable Definition

Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. These are often the objects that store a collection of data.

Immutable Definition

Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.

List of Mutable and Immutable objects

Objects of built-in type that are mutable are:

  • Lists
  • Sets
  • Dictionaries
  • User-Defined Classes (It purely depends upon the user to define the characteristics) 

Objects of built-in type that are immutable are:

  • Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)
  • Strings
  • Tuples
  • Frozen Sets
  • User-Defined Classes (It purely depends upon the user to define the characteristics)

Object mutability is one of the characteristics that makes Python a dynamically typed language. Though Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the intransitive nature of immutability.

Objects in Python

In Python, everything is treated as an object. Every object has these three attributes:

  • Identity – This refers to the address that the object refers to in the computer’s memory.
  • Type – This refers to the kind of object that is created. For example- integer, list, string etc. 
  • Value – This refers to the value stored by the object. For example – List=[1,2,3] would hold the numbers 1,2 and 3

While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.

Check out this free python certificate course to get started with Python.

Mutable Objects in Python

I believe, rather than diving deep into the theory aspects of mutable and immutable in Python, a simple code would be the best way to depict what it means in Python. Hence, let us discuss the below code step-by-step:

#Creating a list which contains name of Indian cities  

cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]

# Printing the elements from the list cities, separated by a comma & space

for city in cities:
		print(city, end=’, ’)

Output [1]: Delhi, Mumbai, Kolkata

#Printing the location of the object created in the memory address in hexadecimal format


Output [2]: 0x1691d7de8c8

#Adding a new city to the list cities


#Printing the elements from the list cities, separated by a comma & space 

for city in cities:
	print(city, end=’, ’)

Output [3]: Delhi, Mumbai, Kolkata, Chennai

#Printing the location of the object created in the memory address in hexadecimal format


Output [4]: 0x1691d7de8c8

The above example shows us that we were able to change the internal state of the object ‘cities’ by adding one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.

Let us now discuss the term IMMUTABLE. Considering that we understood what mutable stands for, it is obvious that the definition of immutable will have ‘NOT’ included in it. Here is the simplest definition of immutable– An object whose internal state can NOT be changed is IMMUTABLE.

Again, if you try and concentrate on different error messages, you have encountered, thrown by the respective IDE; you use you would be able to identify the immutable objects in Python. For instance, consider the below code & associated error message with it, while trying to change the value of a Tuple at index 0. 

#Creating a Tuple with variable name ‘foo’

foo = (1, 2)

#Changing the index[0] value from 1 to 3

foo[0] = 3
TypeError: 'tuple' object does not support item assignment 

Immutable Objects in Python

Once again, a simple code would be the best way to depict what immutable stands for. Hence, let us discuss the below code step-by-step:

#Creating a Tuple which contains English name of weekdays

weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’

# Printing the elements of tuple weekdays


Output [1]:  (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)

#Printing the location of the object created in the memory address in hexadecimal format


Output [2]: 0x1691cc35090

#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator to add a new imaginary day in the tuple ‘weekdays’

weekdays  +=  ‘Pythonday’,

#Printing the elements of tuple weekdays


Output [3]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Pythonday’)

#Printing the location of the object created in the memory address in hexadecimal format


Output [4]: 0x1691cc8ad68

This above example shows that we were able to use the same variable name that is referencing an object which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python program manager created a new object in the memory address and the variable name ‘weekdays’ started referencing the new object with eight elements in it.  Hence, we can say that the object which is a type of tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.

Also Read: Understanding the Exploratory Data Analysis (EDA) in Python

Where can you use mutable and immutable objects:

Mutable objects can be used where you want to allow for any updates. For example, you have a list of employee names in your organizations, and that needs to be updated every time a new member is hired. You can create a mutable list, and it can be updated easily.

Immutability offers a lot of useful applications to different sensitive tasks we do in a network centred environment where we allow for parallel processing. By creating immutable objects, you seal the values and ensure that no threads can invoke overwrite/update to your data. This is also useful in situations where you would like to write a piece of code that cannot be modified. For example, a debug code that attempts to find the value of an immutable object.

Watch outs:  Non transitive nature of Immutability:

OK! Now we do understand what mutable & immutable objects in Python are. Let’s go ahead and discuss the combination of these two and explore the possibilities. Let’s discuss, as to how will it behave if you have an immutable object which contains the mutable object(s)? Or vice versa? Let us again use a code to understand this behaviour–

#creating a tuple (immutable object) which contains 2 lists(mutable) as it’s elements

#The elements (lists) contains the name, age & gender 

person = (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the tuple


Output [1]: (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format


Output [2]: 0x1691ef47f88

#Changing the age for the 1st element. Selecting 1st element of tuple by using indexing [0] then 2nd element of the list by using indexing [1] and assigning a new value for age as 4

person[0][1] = 4

#printing the updated tuple


Output [3]: (['Ayaan', 4, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format


Output [4]: 0x1691ef47f88

In the above code, you can see that the object ‘person’ is immutable since it is a type of tuple. However, it has two lists as it’s elements, and we can change the state of lists (lists being mutable). So, here we did not change the object reference inside the Tuple, but the referenced object was mutated.

Also Read: Real-Time Object Detection Using TensorFlow

Same way, let’s explore how it will behave if you have a mutable object which contains an immutable object? Let us again use a code to understand the behaviour–

#creating a list (mutable object) which contains tuples(immutable) as it’s elements

list1 = [(1, 2, 3), (4, 5, 6)]

#printing the list


Output [1]: [(1, 2, 3), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format


Output [2]: 0x1691d5b13c8	

#changing object reference at index 0

list1[0] = (7, 8, 9)

#printing the list

Output [3]: [(7, 8, 9), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format


Output [4]: 0x1691d5b13c8

As an individual, it completely depends upon you and your requirements as to what kind of data structure you would like to create with a combination of mutable & immutable objects. I hope that this information will help you while deciding the type of object you would like to select going forward.

Before I end our discussion on IMMUTABILITY, allow me to use the word ‘CAVITE’ when we discuss the String and Integers. There is an exception, and you may see some surprising results while checking the truthiness for immutability. For instance:
#creating an object of integer type with value 10 and reference variable name ‘x’ 

x = 10

#printing the value of ‘x’


Output [1]: 10

#Printing the location of the object created in the memory address in hexadecimal format


Output [2]: 0x538fb560

#creating an object of integer type with value 10 and reference variable name ‘y’

y = 10

#printing the value of ‘y’


Output [3]: 10

#Printing the location of the object created in the memory address in hexadecimal format


Output [4]: 0x538fb560

As per our discussion and understanding, so far, the memory address for x & y should have been different, since, 10 is an instance of Integer class which is immutable. However, as shown in the above code, it has the same memory address. This is not something that we expected. It seems that what we have understood and discussed, has an exception as well.

Quick checkPython Data Structures

Immutability of Tuple

Tuples are immutable and hence cannot have any changes in them once they are created in Python. This is because they support the same sequence operations as strings. We all know that strings are immutable. The index operator will select an element from a tuple just like in a string. Hence, they are immutable.

Exceptions in immutability

Like all, there are exceptions in the immutability in python too. Not all immutable objects are really mutable. This will lead to a lot of doubts in your mind. Let us just take an example to understand this.

Consider a tuple ‘tup’.

Now, if we consider tuple tup = (‘GreatLearning’,[4,3,1,2]) ;

We see that the tuple has elements of different data types. The first element here is a string which as we all know is immutable in nature. The second element is a list which we all know is mutable. Now, we all know that the tuple itself is an immutable data type. It cannot change its contents. But, the list inside it can change its contents. So, the value of the Immutable objects cannot be changed but its constituent objects can. change its value.


1. Difference between mutable vs immutable in Python?

Mutable ObjectImmutable Object
State of the object can be modified after it is created.State of the object can’t be modified once it is created.
They are not thread safe.They are thread safe
Mutable classes are not final.It is important to make the class final before creating an immutable object.

2. What are the mutable and immutable data types in Python?

  • Some mutable data types in Python are:

list, dictionary, set, user-defined classes.

  • Some immutable data types are: 

int, float, decimal, bool, string, tuple, range.

3. Are lists mutable in Python?

Lists in Python are mutable data types as the elements of the list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created.
(Examples related to lists have been discussed earlier in this blog.)

4. Why are tuples called immutable types?

Tuple and list data structures are very similar, but one big difference between the data types is that lists are mutable, whereas tuples are immutable. The reason for the tuple’s immutability is that once the elements are added to the tuple and the tuple has been created; it remains unchanged.

A programmer would always prefer building a code that can be reused instead of making the whole data object again. Still, even though tuples are immutable, like lists, they can contain any Python object, including mutable objects.

5. Are sets mutable in Python?

A set is an iterable unordered collection of data type which can be used to perform mathematical operations (like union, intersection, difference etc.). Every element in a set is unique and immutable, i.e. no duplicate values should be there, and the values can’t be changed. However, we can add or remove items from the set as the set itself is mutable.

6. Are strings mutable in Python?

Strings are not mutable in Python. Strings are a immutable data types which means that its value cannot be updated.

Join Great Learning Academy’s free online courses and upgrade your skills today.

Original article source at:


Ray  Patel

Ray Patel


Angry birds In Python With Source Code

Please scroll down and click on the download button to download the Angry Birds In Python With Source Code for free

The Angry Birds project is coded in Python. This game is a simple shooting game. While playing the game, all you have to do is just use your mouse to change the direction of the angry birds. And finally, you can use the right-click button of the mouse to shoot the angry birds to kill the prey. Also, it has a simple and clean GUI for easy gameplay. The game is an interesting game.

About System

The project file contains python scripts (,,,, Talking about the gameplay, the player has to shoot the prey from any suitable direction with the help of angry birds. The player must shoot the angry birds to the prey and injure it to make it count. Moreover, the player has to aim with the angry birds and shoot them to the prey and kill them to win the score. Also, the PC controls of this game are also simple. You can use your mouse to make an aim at any direction. Likewise, the gameplay design is so simple that the user won’t find it difficult to use and understand.

#pygame #python projects #python projects #python #source code #angry birds in python with source code

Ray  Patel

Ray Patel


Stack Tower In Python With Source Code

Please scroll down and click on the download button to download the Stack Tower In Python With Source Code for free

The Stack Tower project is a simple project in Python. This game is a simple stack-building game. In this game, the player has to make a stack tower by piling up tiles one after another, to get a point as a score. The user can play the game until he/she fails to place the tiles/stacks over the building tower. There is a simple and clean GUI for easy gameplay. Here, the player has to use the mouse to place the stack at another stack. The game is an interesting game.

About System

The project file contains python scripts ( Talking about the gameplay, the user has to build a stack tower without making the tiles/pieces fall. The player has to pile up the pieces to form the stack tower and make points. The pc control of the game is very simple. You just have to use the cursor to click the moving tiles/pieces in order to make it stop for building the tower. The gameplay design is so simple that the user won’t find it difficult to use and understand.

#pygame #python projects #python projects #python #source code #stack tower in python with source code