Python- Data Types

Peggie Mishra
8 min readOct 19, 2022

Python is a high level general purpose programming language used today in varieties of field like Data Science, Data analytics, Machine Learning etc

In real life there are multiple applications across the globe which uses python behind the scenes, some of them being the Fortune 500 giants - Uber, Facebook(Meta), Quora, Git Hub etc.

Unlike other programming language, Python offers one of a kind data types like String, List, Tuple, Dictionary,Sets. Each of them provides a unique solutions to data industry.

It also supports old school data types like other programming languages C,Java, C++, Shell etc int, decimal, float, boolean etc.

Keywords in python are reserved for specific operations, using it might lead to error or warnings. It is recommended to use your own defined names for custom variables, functions and other python related definitions.

Data Type s— Python representation

Let us go through some of the data types which is majorly used and discussed one by one.

Strings:

String is data type in python which stores series of character values.It is stored inside quotes (single’’/double””). The string data types are immutable, which means a string value cannot be updated.Strings can be accessed using indexing starting from 0 till length-1.

Example:
‘This is a string’ , “This is a string”

We can use apostrophe and quotes inside string given being alternatively used.Eg:

”One of Python’s strengths is it’s diverse and supportive community.”
‘Hey there,”Can you share that link”’

Accessing strings via indexing

Code Snippet:
str="hello"
print(str[0])
Output:
h

Some the programming needs for string might be :

a) Convert the input from user into lowercase,uppercase,titlecase etc

Code Snippet:
user_input=input("<: ")
print(user_input.lower())
print(user_input.upper())
print(user_input.title())
Output:
<: Hello There
hello there
HELLO THERE
Hello There

b)Join the string given by user like first_name,last_name and output full_name. Below example make use of f string formatter.

Code Snippet:
first_name=input("Enter first name: ")
second_name=input("Enter second name: ")
full_name=print(f'{first_name} {second_name}')
Output:
Enter first name: John
Enter second name: Miller
John Miller

c) Combine tabs and newlines in a single string

Code Snippet:
print("Languages:\n\tPython\n\tC\n\tJavaScript")
Output:
Languages:
Python
C
JavaScript

d) Stripping off leading and trailing spaces or only leading spaces or only trailing spaces.

Code Snippet:
language = ' python '
print(language.strip())
print(language.rstrip())
print(language.lstrip())
Output:
python
python
python

Lists:

List is data type in python storing collection of items which might be alphanumerical values.Lists are mutable meaning we can change the items inside list.List is represented within square brackets[] with items separated by comma. Items in lists can be accessed via indexes from 0 to length -1.Lists can be constructed using list() constructor.

Lists supports various methods for operations around it.Some of them includes append(),insert(),pop(),remove(),delete(),reverse(),sort(),sorted().

Below are working examples of list and its operations:

a)Creating first list and accessing it.

Code Snippet:
first_list=['a','b','c','d'] or first_list=list(('a','b','c','d'))
print(first_list) #print full list
print(first_list[0]) #print first item of list
print(first_list[-1] #print last item of list
Output:
['a', 'b', 'c', 'd']
a
d

b) Changing items in a list:

Code Snippet:
first_list=['a','b','c','d']
print(first_list) #before assignment
first_list[0]='q'
print(first_list) #after assignment
Output:
['a', 'b', 'c', 'd']
['q', 'b', 'c', 'd']

c)Append/Insert items into list:

Append inserts the element to last item of the list.Insert insert the element at the given index and shifts remaining items to right of the list .

Code Snippet:
first_list=['a','b','c','d']
print(first_list) #before operations
first_list.append('e') ##append
print(first_list) #after operations
first_list.insert(0,'q') ##insert
print(first_list) #after operations
Output:
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']
['q', 'a', 'b', 'c', 'd', 'e']

d)Remove/Delete/Pop items from list:

Remove operation removes the mentioned item value from list.Delete operation deletes the item from mentioned index.Pop operation pops the item from last.

Code Snippet:
first_list=['a','b','c','d']
print(first_list) #before operations
del(first_list[0]) #delete based on index
print(first_list)
popped_items=first_list.pop() #pop last item
print(popped_items)#print popped item
print(first_list) #after operations
first_list.remove('c') #remove item by value
print(first_list)
Output:
['a', 'b', 'c', 'd']
['b', 'c', 'd']
d
['b', 'c']
['b']

e)Sorting/Reversing a list

Sort sorts the list in place permanently, with Reverse=True sorts in reverse order.Sorted sorts the list but not permanently, with Reverse=True sorts in reverse order.

Code Snippet:
first_list=['a','b','c','d']
print(first_list) #before operations
first_list.sort() #sorts the list in place
print(first_list)
first_list.sort(reverse=True)
print(first_list)
new_list=sorted(first_list) #sorts and create new list
print(first_list)
print(new_list) #new sorted list
reverse_sorted_list=sorted(first_list,reverse=True)
print(reverse_sorted_list)
Output:
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
['d', 'c', 'b', 'a']
['d', 'c', 'b', 'a']
['a', 'b', 'c', 'd']
['d', 'c', 'b', 'a']

Reverse reverses the list in place permanently.

Code Snippet:
first_list=['a','b','c','d']
print(first_list) #before operations
first_list.reverse()
print(first_list)
Output:
['a', 'b', 'c', 'd']
['d', 'c', 'b', 'a']

f)Finding length of list

Len() is used to determine length of list which starts from 1.

Code Snippet:
first_list=['a','b','c','d']
print(first_list)
print(len(first_list))
Output:
['a', 'b', 'c', 'd']
4

Lists can also be looped through using different looping methods in python like for, while etc

Code Snippet:
first_list=['a','b','c','d']
for item in first_list:
print(item * 2)
Output:
aa
bb
cc
dd
Code Snippet:first_list=['a','b','c','d']
second_list=[item*2 for item in first_list] ##using list comprehension for creating second list
print(second_list)
Output:['aa', 'bb', 'cc', 'dd']

Lists can also be sliced through its elements using colon (:) operator which are called start index , end index and step up value.

Start(x): Starting index position, index inclusive.

End(y): End index position, index exclusive.

Step up(z): Step up by default is +1 if empty or None.Sign of step up (z) indicates forward or backward direction of the step. Absolute value of z indicates the step size

When step up is +ve, defaults for start(x) is 0 and end(y)is len of list.
When step up is -ve ,defaults for start(x) is -1 ,end(y) is -(len+1) and list will be sliced from end to beginning.

Negative Index(-1) is considered the last element , -2 second last element and so on.

-ve Index: -6-5-4-3-2-1
my_list= [1,2,3,4,5,6]
+ve Index: 0 1 2 3 4 5
my_list[x:y:z] #x-start index, z-step up, y-end index
z,y,z can be positive, negative or blank(takes default values)
We can also use None for arguments for x,y,z.

If the list indices are out of bounds, it will automatically truncate then at the right places i.e if the indices don’t fall within the range of the number of elements in the list, we can return an empty list

Code Snippet:
my_list=[1,2,3,4,5,6]
print(my_list[100:100:-100])
Output:[]

Few examples of list slicing:

Code Snippet:
my_list=[1,2,3,4,5,6]
print(my_list[0:2])
print(my_list[:2])
print(my_list[1:4:1])
print(my_list[::2])
print(my_list[2::-1])
print(my_list[-1:2:])
print(my_list[::-1])
print(my_list[:None:-1])
print(my_list[-2:1])
print(my_list[1:-1])
Output:
[1, 2]
[1, 2]
[2, 3, 4]
[1, 3, 5]
[3, 2, 1]
[] ##empty list as +1 step-up is forward and no index 2 at forward movement
[6, 5, 4, 3, 2, 1] ##shortcut for reversing a list
[6, 5, 4, 3, 2, 1] ##shortcut for reversing a list
[] ##empty list as +1 step-up is forward and no index 1 at forward movement
[2,3,4,5] #start from 1st index and go till (-1) last index

Tuples:

Tuples are collections of items similar to list but it is immutable and is enclosed inside parenthesis ().Similar to lists we can loop over values in tuple.Tuple length can be determined using len().Tuple can be constructed using tuple() constructor.Tuple can be accessed using indexes like lists which can be positive/negative/zero.Tuple can be sliced.

Eg my_tuple=(1,2,3) or my_tuple=tuple((1,2,3))

We cannot change item inside tuple once it is defined thus, immutable.

my_tuple[0]=4 #TypeError: ‘tuple’ object does not support item assignment

List can be converted into tuple via type casting in python.

my_list=list(my_tuple) ==>[1, 2, 3]

Dictionaries:

Dictionary is collection of key-value pairs.It has major application in real -world scenarios.Each key is connected to a value by colon (:) which can be number, string, list, any other dictionary or any user defined object.It is wrapped under curly braces {}.Individual key value pairs are separated by comma(,)

Player = {‘color’ : ‘green’, ‘points’: 5}

Dictionary operations:

##Accessing dictionary valueCode Snippet
player={'color':'green','count':5}
print(player['color'])
Output:
green
##assigning key value to a variable
player_colour=player['color']
print(player_colour)
Output:
green

##Adding key-value dictionary
player['weight']=56
print(player)
Output:
{'color': 'green', 'count': 5, 'weight': 56}
##Empty Dictionaryplayer2={}##Modifying Values in Dictionaryplayer['color']='yellow'
print(player)
Output:
{'color': 'yellow', 'count': 5}
##Removing key value pairs
del player['color']
print(player)
Output:
{'count': 5}
deleted key-value pair is removed permanentlyUsing keys in [] to retrieve the data might cause error when keys not present are tried to get accessed.print(player['height'])Error: KeyError: 'height'Using get to do above resolves the issue.Get takes first argument as key name and second as default value.If no default value provided it still doesn't throw error and returns None object.print(player.get('height'))
print(player.get('height','hello'))
Output:
None
hello
#Looping through dictionaryfor k, v in player.items() #k , v can be named anything represents key,valuefor k in player.keys() #loop through keys by default it is keys eg for k in playerfor k in sorted(player.keys()) #loop through sorted keysfor v in sorted(player.values()) #loop through values
for v in set(player.values()) # loop through unique values
#Nesting --list of dict-- dict of list--dict of dict list of dictionaryPlayer1 = {‘color’ : ‘green’, ‘points’: 5}
Player2 = {‘color’ : ‘yellow’, ‘points’: 6}
Player=[Player1,Player2]dictionary of list
Player1 = {‘color’ : ['green’,'yellow'], ‘points’: 5}Dictionary of dictionaryPlayer = {Player1 = {‘color’ : ‘green’, ‘points’: 5},
Player2 = {‘color’ : ‘yellow’, ‘points’: 6} }

Sets

Sets are collection of items which are unordered and unique.Since sets are unordered we cannot access items using indexing method.Set is represented by value in curly braces {},separated by comma.Sets are mutable i.e elements of sets can be modified anytime but not via slicing or indexing via methods.Add(),Update(),Union(),Intersection(),difference() are some of sets methods.Sets supports most of the mathematical operators.Sets cannot be nested with mutable item like list and dictionary. It can however contain tuple,integer,float,string etc. Set can also be created using set constructor (set()). Set() creates empty set

Code Snippet:my_set={'a','b','c','c','a','b'}
print(my_set)
Output: {‘a’, ‘c’, ‘b’}#Nesting set with list results to error my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'
#Union is performed using | operator or union()
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

print(A|B) or print(A.union(B))
Output:{1, 2, 3, 4, 5, 6, 7, 8}#Intersection is performed using & operator or intersection()print(A & B) or print(A.intersection(B))Output:{4, 5}#Difference is performed using - or difference()print(A-B) or print(A.difference(B))
Output: {1, 2, 3}
Iteration can be done using loop:
for letter in set("A"):

Frozen Sets:

Frozen Sets are collection of items which are similar to sets but are immutable. It does not support mutable methods like add(),update(),remove(),discard() etc. It supports mathematical methods and other methods which doesn't impact the originality of set.It can be defined via frozenset() eg: A = frozenset([1, 2, 3, 4])

A = frozenset([1, 2, 3, 4, 5])
print(type(A))
Output: <class 'frozenset'>##Changing set results error.A.add(6)
AttributeError: 'frozenset' object has no attribute 'add'

As we saw python data types have so many applications and varieties.We can use it many applications like web,data visualisation & data science etc.

--

--