Variables in Python

Updated on May 20, 2019
Sam Shepards profile image

I'm a software developer with a great interest in data analysis and statistics.

Just like any programming language, variables in Python are reserved memory locations to store values in them. Unlike other programming languages like C, C++, Java, etc, Python does not require one to explicitly declare the type of the variable before assigning a value to it. In fact, memory is reserved for the variable as soon as a value is assigned to it and the interpreter takes care of it at runtime.

Assigning Values to Python Variables

Consider the following code:

#!/usr/bin/python3
a = 10;
b = 20;
name = "Sammy"
print(a)
print(b)
print('Hello ', name)
print(a+b)

The output of the above code will be:

10
20
Hello Sammy
30     

Let us analyze the above code to learn more.

Notice the first line starting with #!. This is called a shebang or hash-bang or pound-bang line. This is particularly useful in case of Unix environment where you can convert the .py file into an executable and run it as:

./test.py

The hash-bang line in the starting of the file serves as an interpreter directive and gives the file as an input to the python interpreter located at /usr/bin/python3.

Since a and b are implicitly reserved spaces and treated as numbers by the interpreter, the last line prints the sum of a and b.

Dealing With Multiple Assignments

If more than one variables need to be initialized with the same value, Python allows you to do the declaration and assignment in a single line. Eg:

#!/usr/bin/python3
x=y=z=0
print(x)
print(y)
print(z)

The output for the above code will be:

0
0
0

It is perfectly legal to initialize heterogeneous values in the following way:

#!/usr/bin/python3
name, age, dob = 'Sammy', 25, "01-01-1990"
print("Name: ", name)
print("Age: ", age)
print("DOB: ", dob)

The output of the above code will be:

Name:  Tom
Age: 25
DOB:  01-01-1990

Notice that unlike other languages, it is perfectly fine to use single quotes or double quotes for representing a String value. However, care should be taken not to mix these two and use different quotes at the start and end of the String literal.

Data Types

In the previous section, we saw a glimpse of two data types in Python – numbers, and strings. In this section, we will learn more about the data types in python.

Python has 5 standard data types.

Numbers

As the name suggests, the number data type is used to store numerical values. Numbers are represented as objects and memory is allocated to them as soon as we assign them a value. It is possible to use del statement to delete the reference to a number object.

There are four types of numbers supported by Python. They are:

  • Int – represents signed integers
  • Long – long values represented with a trailing L to distinguish between int and long types.
  • Float – floating point values.
  • Complex – complex numbers that are represented as a+bi where a and b are real values and I represent the imaginary unit of the complex number.

Strings

They represent a continuous set of characters enclosed in single or double quotation marks. To get a character at a given position I, we use str[i]. We can get substrings using the slice operator[:]. Just like Java, string concatenation can be done using a + sign. It is possible to repeat the string n times by using * operator.

Let us learn more about this with an example:

#!/usr/bin/python3
myString = "Welcome To String Tutorial!"
print (myString)          # Prints complete string
print (myString[0])       # Prints first character of the string
print (myString[8:10])    # Prints characters starting from 3rd to 5th. So, should print "To" alone.
print (myString[8:])      # Prints string starting from the second word "To". The second word's starting letter is at myString[8]
print (myString * 4)      # Prints the string four times.
print (myString + "TEST") # Prints concatenated string with Test

Output of the above program will be:

Welcome To String Tutorial!
W
To
To String Tutorial!
Welcome To String Tutorial!Welcome To String Tutorial!Welcome To String Tutorial!Welcome To String Tutorial!
Welcome To String Tutorial!TEST

Lists

Python Lists have some similarities and some differences with traditional arrays in C, C++, Java, etc. The similarity between the Python list and an array in a language like Java is that the list is represented using comma separated values enclosed inside square brackets. But unlike arrays which always contain homogeneous data types, lists can contain heterogeneous types.

Almost all the operations we saw in the example written for Strings subsection are applicable in case of lists. The ith element in case of a list can be accessed using list[i]. Using a slice operator, we can get elements in a range of indices of the list. Using + sign, we can concatenate two lists. Using *, we can repeat a list.

#!/usr/bin/python3

myList = [ 'Welcome', "To" , "List", 'Tutorial', 3.0 ]
studentData = ['john', "smith", 29, 415312]

print(myList)               # Prints complete list
print(myList[0])            # Prints first element of myList
print(studentData[1:3])     # Prints smith and 29 as they are 2nd and 3rd element of the list.
print(myList[2:])           # Prints elements starting from 3rd element
print(studentData * 2)      # Prints list studentDatatwo times
print(myList + studentData) # Prints concatenated lists

The output of the above program will be:

['Welcome', 'To', 'List', 'Tutorial', 3.0]
Welcome
['smith', 29]
['List', 'Tutorial', 3.0]
['john', 'smith', 29, 415312, 'john', 'smith', 29, 415312]
['Welcome', 'To', 'List', 'Tutorial', 3.0, 'john', 'smith', 29, 415312]

Tuples

Tuples are similar to lists where individual elements are separated using commas. All the operations that were discussed in the previous example for Lists subsection are applicable for tuples as well.

Unlike lists, tuples are grouped using parentheses() instead of square brackets[]. Moreover, elements in a tuple are not modifiable but a list can be modified once it is created.

#!/usr/bin/python3

firstTuple = ( 'Welcome', "To" , "List", 'Tutorial', 3.0  )
firstList = [ 'Welcome', "To" , "List", 'Tutorial', 3.0  ]
secondTuple = ('john', "smith", 29, 415312)

print(firstTuple)               # Prints complete tuple
print(firstTuple[0])            # Prints first element of the firstTuple
print(firstTuple[1:3])          # Prints elements starting from 2nd till 3rd of firstTuple
print(firstTuple[2:])           # Prints elements starting from 3rd element of firstTuple
print(secondTuple * 3)            # Prints the secondTuple three times
print(firstTuple + secondTuple)   # Prints concatenated tuples

firstList[2] = 1000     # Valid syntax with list
print("firstList values after modification:")
print(firstList)
firstTuple[2] = 1000    # Invalid syntax with tuple
print("firstTuple values after modification:")
print(firstTuple)

The output of the above program will be:

('Welcome', 'To', 'List', 'Tutorial', 3.0)
Welcome
('To', 'List')
('List', 'Tutorial', 3.0)
('john', 'smith', 29, 415312, 'john', 'smith', 29, 415312, 'john', 'smith', 29, 415312)
('Welcome', 'To', 'List', 'Tutorial', 3.0, 'john', 'smith', 29, 415312)
firstList values after modification:
['Welcome', 'To', 1000, 'Tutorial', 3.0]
Traceback (most recent call last):
  File "G:\workspaces\py_ws\MyProj\org\pythontutorials\examples\TupleVsList.py", line 22, in <module>
    firstTuple[2] = 1000    # Invalid syntax with tuple
TypeError: 'tuple' object does not support item assignment

Notice the error thrown at end of the output while we try to modify a tuple’s element. This is because tuples are treated as read-only lists.

Dictionary

Dictionaries in Python consist of comma-separated key-value pairs enclosed within curly braces{}. Keys in a dictionary are usually numbers or strings. Values can be of any type and can be assigned or accessed using square brackets.

#!/usr/bin/python3

firstDict = {}
firstDict['Welcome'] = "Welcome To The Tutorial"
firstDict[2]     = "This is second value"

studentDict = {'firstName': 'john','lastName':'Smith', 'age': 29, 'studentId':415312}


print(firstDict['Welcome']) # Prints value for 'Welcome' key
print(firstDict[2])         # Prints value for 2 key
print(studentDict)          # Prints complete studentDict
print(studentDict.keys())   # Prints all the keys of studentDict
print(studentDict.values()) # Prints all the values of studentDict

The output of the above program will be:

Welcome To The Tutorial
This is second value
{'studentId': 415312, 'age': 29, 'lastName': 'Smith', 'firstName': 'john'}
dict_keys(['studentId', 'age', 'lastName', 'firstName'])
dict_values([415312, 29, 'Smith', 'john'])

To Sum Up

In this tutorial, we saw how Python handles variables and allocates memory for them. We also learned how Python’s standard data types are simple yet different from those in other languages. It is the simplicity of the language which makes it the language of choice for most applications these days.

© 2019 Sam Shepards

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://turbofuture.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)