This blog explains the data types used in Python at a basic level.
Basic Data Types
The following are the data types in Python.
Ā | Python Keyword | Description | Example |
1 | int | Used for integers | a = 100 |
2 | float | Used for float point number | x=100.5 |
3 | bool | BooleanĀ type True or False | x=True |
4 | str | String - Sequence of ASCII character | x = 'hello' |
5 | list | List of any other data types | x = [1,2 3,4] |
6 | tup | Types - similar to lists but immutable | x = (1,2,3) |
7 | set | Sets - Unique set of values | x=set([1,2,3]) |
8 | dict | Dictionaries - A map of key-value pair | x={"k1":1, "k2:"2} |
At the basic level for data types like int, float and bool you just perform basic arithmetic operations.
Run the below code and observe the output to knowĀ
x=4
y=20
print(x+y)
print(x-y)
print(x*y)
print(y/4)
print(y%4)
x = 10.0
y=25.0
print(x+y)
print(x-y)
print(x*y)
print(y/x)
print(y%4)
Output is
24
-16
80
5
0
35.0
-15.0
250.0
2.5
1.0
Ā
Strings
As explained above string is a continuous sequence of characters. The keyword for strings isĀ str
. It is represented either in a single quote or a double quote.
Example s='Hello World!'
Some of the basic operations on string are, slicing, indexing, searching, joining two strings, etc...
Traverse the Strings
s='Hello World!'
for c in s:
print(c)
Output is
H
e
l
l
o
W
o
r
l
d
!
String Indexing
Indexing starts from 0 and ends at the length of the string - 1
.
s='Hello World!'
s[0]
s[6]
Output is
H
W
Strings support negative indexing
. -1 is the last character in the string.
In the case of negative indexing, actual indexing is calculated as (string length - negative index)
s='Hello World!'
print(s[-1])
print(s[-6])
Output isĀ
!
W
Substrings or Slicing
You can access substrings from slicing.Ā
Syntax is s[start:end:step]
. All three start, end and step are optional. The defaultĀ for the start
is 0, the end
is the length of the string and the step
is 1
Importnat Notes:Ā start is included whereas end is excluded meaning s[2:5] results include s[2] but exclude s[5].
Run the below code and observe.
s='Hello World!'
print(s[2:6])
print(s[3:9:2])
print(s[4:])
print(s[:6])
print(s[:])
Output is
llo
l o
o World!
Hello
Hello World!
Joining String
You can join two strings by simply addition
s1='Hello '
s2='World!'
s1+s2
Output isĀ
Hello World!
String Reverse
You can reverse a string with negative indexing
and substring
s='Hello World!'
print(s[::-1])
Output is
!dlroW olleH
List
Lists in Python are collections of data types. It is denoted by []. The keyword for lists is list
. Unlike strings lists are mutable
.
Example is l = [1, 2, 3, 4]
Some of the operations are lists accessing/getting (indexing), deleting, slicing and joining.
Traversing the list
You can iterate over the list with a for loop similar to strings.
l = [1, 2, 3, 4]
for e in l:
print(e)
Output is
1
2
3
4
Indexing the lists
You can access elements in the list with indexing similar to strings.
Similar to string, list indexing starts from 0 and ends at the number of elements in the list - 1
.
l = [1, 2, 3, 4]
print(l[0])
print(l[3])
Output is
1
4
Similar to strings lists also supportĀ negative indexing
. -1 is the last element in the list.
In the case of negative indexing, actual indexing is calculated as (number of elements in the list - negative index)
l = [1, 2, 3, 4]
print(l[-1])
print(l[-3])
Output is
4
2
Slicing the list
Using indexing you can get a partial list or sublist is called slicing the list.
Syntax is list[start:end: step]
. All three start, end and step are optional. The defaultĀ for the start
is 0, the end
is the length of the string and the step
is 1
l = [10, 13, 9, 8, 15, 20, 34, 5, 3, 60]
# Print the complete list
print(l[:])
# From index 2 to end of the list
print(l[2:])
# From zero to 3
print(l[:4])
# From 2 to end of teh list in step 2
print(l[2::2])
Output is
[10, 13, 9, 8, 15, 20, 34, 5, 3, 60]
[9, 8, 15, 20, 34, 5, 3, 60]
[10, 13, 9, 8]
[9, 15, 34, 3]
Joining the lists
You can join two lists by simply addition
l1 = [10, 13, 9, 8, 15]
l2 = [20, 34, 5, 3, 60]
print(l1+l2)
Output is
[10, 13, 9, 8, 15, 20, 34, 5, 3, 60]
Reversing the list
You can reverse a list with negative indexing
and slicing
l = [10, 13, 9, 8, 15, 20, 34, 5, 3, 60]
print(l[::-1])
Output is
[60, 3, 5, 34, 20, 15, 8, 9, 13, 10]
Updating the list
As explained above lists are mutable, so you can update the list.
You can add elements to the list using the append method.Ā
You can add by append
method and delete by pop
method
l = [10, 13, 9, 8, 15, 20, 34, 5, 3, 60]
print('Initial list: ', l)
# Adding 1 to the list
l.append(1)
l.append(70)
l.append(18)
print('Update list after append list: ', l)
x = l.pop()
print('Update list after append list: ', l)
print('poped element in the list: ', x)
Output is
Initial list: [10, 13, 9, 8, 15, 20, 34, 5, 3, 60]
Update list after append list: [10, 13, 9, 8, 15, 20, 34, 5, 3, 60, 1, 70, 18]
Update list after append list: [10, 13, 9, 8, 15, 20, 34, 5, 3, 60, 1, 70]
poped element in the list: 18
Tuple
Tuples are similar to lists but immutable
. It is denoted by parentheses ()
.Ā The keyword for tupels is tuple
.Ā
Tuples are used mostly when we don't want to change values. Another good use case is returning multiple values from a function.
The most used operations are iterating and indexing
Traversing the Tuple
You can iterate over the tuples with a for loop similar to lists.
Ā
t=(1,2,3,6,7)
for i in t:
print(i)
Output isĀ
1
2
3
6
7
Indexing the tuples
You can access elements in the tuple with indexing similar to a list.
Similar to string lists, indexing starts from 0 and ends at the number of elements in the tuple - 1
.
t = (1, 2, 3, 4)
print(t[0])
print(t[3])
Output is
1
4
Similar to lists, tuples also support negative indexing
. -1 is the last element in the list.
In the case of negative indexing, actual indexing is calculated as (numberĀ of elements in the tuple - negative index)
t = (1, 2, 3, 4)
print(t[-1])
print(t[-3])
Output is
4
2
Slicing the Tuples
Using indexing you can get a partial tuple or subtuple is called slicing the tuple.
Syntax is tuple[start:end: step]
. All three start, end and step are optional. The defaultĀ for the start
is 0, the end
is the length of the string and the step
is 1
t = (10, 13, 9, 8, 15, 20, 34, 5, 3, 60)
# Print the complete tuple
print(t[:])
# From index 2 to end of the tuple
print(t[2:])
# From zero to 3
print(t[:4])
# From 2 to end of the tuple in step 2
print(t[2::2])
Output is
[10, 13, 9, 8, 15, 20, 34, 5, 3, 60]
[9, 8, 15, 20, 34, 5, 3, 60]
[10, 13, 9, 8]
[9, 15, 34, 3]
Joining the Tuples
You can join two tuples by simply addition
t1 = (10, 13, 9, 8, 15)
t2 = (20, 34, 5, 3, 60)
print(t1+t2)
Output is
[10, 13, 9, 8, 15, 20, 34, 5, 3, 60]
Reversing the Tuple
You can reverse a list with negative indexing
and slicing
t = (10, 13, 9, 8, 15, 20, 34, 5, 3, 60)
print(t[::-1])
Output is
[60, 3, 5, 34, 20, 15, 8, 9, 13, 10]
Dictionary
Dictionaries are the key-value pairs. This is mostly used data type in Python. This is denoted {}
. The keyword for the dictionary isĀ dict
. They are mutable
.
Example: dict{'Inida': 'Delhi', 'UK': 'London'}
Just to know dictionaries are similar to maps in C++ and Go language.
The most commonly used operations are traversing/iterating, and indexing. The most commonly used methods areĀ keys
, values
, and items
Ā
Indexing the Dictionaries
Dictionary values are accessed by index. Here index may not be a numeric number, it can be a string or tuple.
countryCapitals = { 'India': 'Delhi', 'UK': 'London', 'USA': 'New York' }
print(countryCapitals['India'])
print(countryCapitals['USA'])
Output is
Delhi
New York
Traversing the Dictionaries
Traversing dictionaries in 3 three ways.Ā
keys
method is used to get all the keys and using the same keys you can access values using the index as shown above.
values
method is used to get all the values
items
method is used to get both keys and values as a tuple.
Important Note: Dictionaries can be iterated without any method, in this case, it will return keys.
countryCapitals = { 'India': 'Delhi', 'UK': 'London', 'USA': 'New York' }
print('Iterating using keys')
for country in countryCapitals.keys():
print(country, countryCapitals[country])
print('\nIterating using values')
for capital in countryCapitals.keys():
print(capital)
print('\nIterating using values')
for country, capital in countryCapitals.items():
print(country, capital)
print('\nIterating without method')
for country in countryCapitals:
print(country, countryCapitals[country])
Output is
Iterating using keys
India Delhi
UK London
USA New York
Iterating using values
India
UK
USA
Iterating using values
India Delhi
UK London
USA New York
Iterating without method
India Delhi
UK London
USA New York
Updating the Dictionary
Dictionaries can be modified using indexing. You can add a new element or update the existing value.
employee = { 'Name': 'Rabbani', 'Company': 'Verizon', 'Role': 'Developer' }
print('Initial dictionary')
for key, value in employee.items():
print(key, value)
print('\nUpdating Name')
employee['Name'] = 'Thulasi'
print('Check Name')
print(employee['Name'])
print('\nAdding new key Location')
employee['Location'] = 'India'
print('Check new key Location')
print(employee['Location'])
Output isĀ
Initial dictionary
Name Rabbani
Company Verizon
Role Developer
Updating Name
Check Name
Thulasi
Adding new key Location
Check new key Location
India
Set
Sets are unordered collections of unique elements
Sets are used to store unique data. The keyword for lists is set
. sets are mutable
.
Curly braces {}
or the set()
function can be used to create sets. Note: To create an empty set you have to use set()
, notĀ {}
Example countries = {'India', 'UK', 'USA'}Ā
Basic operarions on sets are similar to lists, like indexing, iterating, slicing, deleting and joining
Traversing the Set
You can iterate over the set with a for loop similar to a list.
countries = {'India', 'UK', 'USA'}
for c in countries:
print(c)
Output is
India
USA
UK
Important Note: Indexing is not supported for set
Updating the Set
You can add a new element with theĀ add
method and delete an element with theĀ pop
method
countries = {'India', 'UK', 'USA', 'Japan'}
print('Initilal set')
for c in countries:
print(c)
print('\nAdding new element')
countries.add('Japan')
print('Updated set')
for c in countries:
print(c)
print('\nRemoving element')
countries.pop()
print('Updated set')
for c in countries:
print(c)
Output is
Initilal set
India
UK
USA
Japan
Adding new element
Update set
India
UK
USA
Japan
Removing element
Update set
UK
USA
Japan
Ā