Hot Posts

hot/hot-posts

Python Datatypes






In this tutorial, we will discuss about different built-in data types such as scalar types or numbers and collection types. Starting from variable declaration we will get into different types such as numbers, list, tuple, strings, set and dictionary in Python with examples and practices. These are the basic data types provided by Python which can be used further to build complex data types.




Variable Declaration in Python

In python, we do not declare a variable explicitly. Variable declaration happens implicitly whenever we assign any value to it and the type is inferred automatically based on the value we assign to it and even the type caan be changed after it has been set. We use type() to identify the variable type.
Examples
x = "abc"

print(x)
print(type(x))

x = 123

print(x)
print(type(x))

Output
abc

123




Different Ways to Assign Variable

Multiple Values
x, y, z = 1, 1.2, "Delhi"

print(x)
print(y)
print(z)

Output
1
1.2
Delhi
x = y = z = "same"

print (x)
print (y)
print (z)
Output
same
same
same



Primitive Scalar Types in Python

Python defines 4 different scalar types - int, float, none type and bool.

int: Python int are signed integer with unlinited precision. Integer literals in Python are described by decimal and can also be specified in binary.
Examples
a = 0b1010 #Binary
b = 10 #Decimal
c = 0o12 #Octal
d = 0xA #Hexadecimal

print(a, b, c, d)

Output
10 10 10 10
We can construct integer by using int() constructor. Below are the examples.
Examples
a = int(10)
b = int(10.4)
c = int("10")
d = int("1000", 2)

print(a, b, c, d)
Output
The last statement converts to integer of base 2.
10 10 10 8

float: float is implemented as IEEE-754 double precision floating point numbers with 53 bits of binary precision which is 15 to 16 bits of decimal precision. Any number containing decimal points or letter 'e' is considered as float by Python.
Examples
a = 4.5
b = 3e8
c = float(10)
d = float("10.5")

print(a, b, c, d)
Output
4.5 300000000.0 10.0 10.5

None: The null value in Python is defined as None.
a = None
print(a)
Output
None

bool: bool type corresponds to either true or false.
print (bool(0))
print (bool(6))
print (bool(0.1))
print (bool([]))
print (bool([1, 2]))
print (bool(""))
Output
False
True
True
False
True
False



Python Strings

Strings in Python are immutable. Strings are immutable sequences of unicode characters. Strings once constructed can not be modified. Strings in Python are delimited with quotes('). We can use single or double quotes.Multi-line strings can be denoted using triple quotes, ''' or """.
a = "abc"
b = 'xyz'
c = "It's my number."

print (a)
print (b)
print (c)

Output
abc
xyz
It's my number.

Strings with Newlines: We can achieve strings with new lines with 2 options - Multiline Strings or Escape Sequences.
Examples
x = str('89.9')
a = "first line"
b = '''first line
second line.'''

c = "Double quote \" string"
d = 'Single quote \' string'
e = "back slash \\"

print(x)
print(a)
print(b)
print(c)
print(d)
print(e)
Output
89.9
first line
first line
second line.
Double quote " string
Single quote ' string
back slash \



Useful String Methods in Python

capitalize() : Converts the first character to upper case
center() : Returns a centered string
count() : Returns the number of times a specified value occurs in a string
endswith() : Returns true if the string ends with the specified value
expandtabs() : Sets the tab size of the string
find() : Searches the string for a specified value and returns the position of where it was found
startswith() : Returns true if the string starts with the specified value
strip() : Returns a trimmed version of the string
len() : Gives the number of character counts in a String e.g. len('lnklsm')
format() : Insert values into Strings. e.g. "My name is {0}".format("John")
Examples
a = "abc"
print(len(a))

b = ",".join(["abc", "def", "ghi"])
print(b)

c = b.split(",")
print(c)

x = "unbreakable".partition("break")
print(x)

departure, seperator, arrival = "Delhi:Mumbai".partition(":")
print(departure, arrival)

Output
3
abc,def,ghi
['abc', 'def', 'ghi']
('un', 'break', 'able')
Delhi Mumbai
My name is John



Python List

List are mutable sequences of objects meaning the elements within the list can be modified, replaced and new elements can be added. List in Python can be heterogenous and represented with [].
Examples
x = [12, "a"]
x.append("b")
x = ["a", "b", 12]
x[2] = "c"

print(x)
print(x[2])
print(x[-1]) #Last element is at index -1

x = list("elements")
print(x)
Output
['a', 'b', 'c']
c
c
['e', 'l', 'e', 'm', 'e', 'n', 't', 's']
x = ["banana", "apple", "orange", "grapes"]

print(x)
print(x[1:3]) #slice, stop not included
print(x[1:])
print(x[:1])

y = x[:] #list copy
print(y)

z = y.copy()
print(z)

a = list(z)
print(a)
Output
['banana', 'apple', 'orange', 'grapes']
['apple', 'orange']
['apple', 'orange', 'grapes']
['banana']
['banana', 'apple', 'orange', 'grapes']
['banana', 'apple', 'orange', 'grapes']
['banana', 'apple', 'orange', 'grapes']
Examples
x = ["banana", "apple", "orange", "grapes"]
print(x)
print("apple" in x)
print(len(x))

x.remove("apple") #element
print(x)

del x[0] #index
print(x)

x.clear() #clear the list
print(x)
Output
['banana', 'apple', 'orange', 'grapes']
True
4
['banana', 'orange', 'grapes']
['orange', 'grapes']
[]



Iterating Over List

We can simply iterate over a Python list using for statement as below and print values.
x = ["orange", "apple", "banana"]
for item in x:
    print(item)

Iterating with the position index and corresponding value
x = ["orange", "apple", "banana"]
for i, v in enumerate(x):
    print(i, v)

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']

for q, a in zip(questions, answers):
    print('What is your {0}?  It is {1}.'.format(q, a))




Python dict

A Dictionary in Python is mutable mappings of keys to values. It is represented as {} with each key value seperated with : and key:value seperated with a comma. The key value pair stored in a Dict does not guarantee the order.
Examples
x = {};
x["name"] = "John"
x["age"] = 34

print(x)
print(x.get("name")) #Preferred way
print(x["name"]) #Exception if the key is not found

x["name"] = "Tom"
print(x)

print("name" in x)

print(len(x))

del x["name"]
print(x)

x.clear()
print(x)
Output
{'name': 'John', 'age': 34}
John
John
{'name': 'Tom', 'age': 34}
True
2
{'age': 34}
{}

.get() does not raise exception for any key that is not present in the dict. Instead, it returns None. Again if you want to return a default value of your choice instead of None then we have following options. Having said that, we can perform nested operations too in such cases without worrying about any exception at run-time.
a = {'name' : 'John', 'city' : 'Delhi'}

print(a.get('address'))

# print(len(a.get('address'))) #Exception as a.get('address') returns None

print(a.get('address', 'NA')) #Returns a default value as NA

print(len(a.get('address', 'NA')))
Output
None
NA
2
Looping
x = {};
x["name"] = "John"
x["age"] = 34

print(x)
for key in x:
  print(key) #Print all key names

for key in x:
  print(x.get(key)) #Print all values

for key, value in x.items():
      print(key, value)
Output
{'name': 'John', 'age': 34}
name
age
John
34
name John
age 34



Iterating Over Dict in Python

We can use for loop to iterate over dict as follow
x = {"name": "John", "city": "Bangalore", "mobile": "8987645634"}
for item in x:
    print(item)
    
The key and corresponding value can be retrieved at the same time using the items() method.
x = {"name": "John", "city": "Bangalore", "mobile": "8987645634"}
for k, v in x.items():
    print(k, v)
    

l



Tuple

A Tuple is a heterogenous immutable sequence similar to List. Being immutable, objects inside a tuple can not be replaced or removed and new elements can not be added. This is the reason why Tuple is faster then List. A tuple is represented with ().
Examples
x = (4, 56, 90, 1)
x + (34,) #Single element tuple not allowed as ("e")
print(x)

y = tuple([1, 2, 3, 4])
print(type(y))

print(3 in y)
Output
(4, 56, 90, 1)

True



Set

A set is an unordered collection of unique, immutable elements. Here, the collection is mutable but elements are immutable.Since, a set is unordered, we can not access it's elements by referring to an index. A set is represented with curly brackets {} similar to map but each item is a single object. Being a collection of immutable objects, a set elements can not be changed but it allows addition of new items.
Examples
x = set();
x = set([12, 54, 56, 56])
print(x)

print(56 not in x)

x.add(78)
print(x)

x.update([67,99]) #multiple elements
print(x)

x.remove(99) # Exception is thrown for unavailable elements
x.discard(99) # no exception

for item in x:
    print(item)


Output
{56, 12, 54}
False
{56, 78, 12, 54}
{67, 99, 12, 78, 54, 56}
67
12
78
54
56



Other Methods in Set
union() : Finds the set theory union of two sets.
intersection() : Finds the set theory intersection of two sets.
difference() : Non-commutative.
symmetric_difference() : Commutative.
issubset() : Check if a given set is subset of the other.

Conclusion

In this tutorial, we discussed about different built-in data types such as numbers, list, tuple, strings, set and dictionary in Python with multiple examples to cover most of the basic scenarios.

Post a Comment

0 Comments