Skip to main content

Data Structures in Python

 Ever wondered  "What is Data Structures?" and "Why is Datastructures", This blog will help you with those questions in Python.


Data structures are a way of organizing and storing data so that they can be accessed and worked with efficiently.Lets Dicuss about the Different Data Types in Python.




Different  Built-in Data Structures of Python:

  • List
  • Dictionary
  • Tuple
  • Sets

Lists

The list type is probably the most commonly used collection type in Python. Despite its name, a list is more like an array in other languages, mostly JavaScript. In Python, a list is merely an ordered collection of valid Python values.

list can be created by enclosing values, separated by commas, in square brackets:

int_list = [1, 2, 3]
string_list = ['abc', 'defghi']

A list can be empty:

empty_list = []

The elements of a list are not restricted to a single data type, which makes sense given that Python is a dynamic language:

mixed_list = [1, 'abc', True, 2.34, None]

A list can contain another list as its element:

nested_list = [['a', 'b', 'c'], [1, 2, 3]]


The elements of a list can be accessed via an index, or numeric representation of their position. Lists in Python are zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1 and so on:



names = ['Alice', 'Bob', 'Craig', 'Diana', 'Eric']

print(names[0]) # Alice

print(names[2]) # Craig

Indices can also be negative which means counting from the end of the list (-1 being the index of the last element). 

So, using the list from the above example:

print(names[-1]) # Eric
print(names[-4]) # Bob

Lists are mutable, so you can change the values in a list:

names[0] = 'Ann'
print(names)
# Outputs ['Ann', 'Bob', 'Craig', 'Diana', 'Eric']



MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the first item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

.append() appends an object to a list:

>>>
>>> a = ['a', 'b']
>>> a
['a', 'b']
>>> a.append(123)
>>> a
['a', 'b', 123]

>>> a = ['a', 'b']
>>> a
['a', 'b']
>>> x = a.append(123)
>>> x
>>> print(x)
None
>>> type(x)
>class 'NoneType'>
>>> a
['a', 'b', 123]

>>> a = ['a', 'b']
>>> a + [1, 2, 3]
['a', 'b', 1, 2, 3]
>>> a
['a', 'b']
>>> a.append([1, 2, 3])
>>> a
['a', 'b', [1, 2, 3]]

>>> a = ['a', 'b']
>>> a
['a', 'b']
>>> a.append('hello')
>>> a
['a', 'b', 'hello']

.extend() extends a list by appending elements from the iterable:

>>>
>>> a = ['a', 'b']
>>> a
['a', 'b']
>>> a.extend([1, 2, 3])
>>> a
['a', 'b', 1, 2, 3]

>>> a = ['a', 'b']
>>> a
['a', 'b']
>>> a += [1, 2, 3]
>>> a
['a', 'b', 1, 2, 3]

.insert(<index>, <obj>) inserts the object <obj> into the list at the specified <index>, pushing the remaining list elements to the right:

>>>
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a.insert(3, 3.14159)
>>> a[3]
3.14159
>>> a
['spam', 'egg', 'bacon', 3.14159, 'tomato', 'ham', 'lobster']

.remove(<obj>) removes the first occurence of the value <obj> and raises a ValueError exception if the value is not present:

>>>
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a.remove('egg')
>>> a
['spam', 'bacon', 'tomato', 'ham', 'lobster']
>>> a.remove('egg')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    a.remove('egg')
ValueError: list.remove(x): x not in list

.clear() removes all items from the list:

>>>
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a.clear
>>> a
[]

.sort(<key=None>, <reverse=False>) sorts the list items in ascending order. An optional function can be used as a key

Here’s an example:

>>>
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a.sort()
>>> a
['bacon', 'egg', 'ham', 'lobster', 'spam', 'tomato']

>>> a += ['Apple', 'Zebra']
>>> a
['bacon', 'egg', 'ham', 'lobster', 'spam', 'tomato', 'Apple', 'Zebra']
>>> a.sort()
>>> a
['Apple', 'Zebra', 'bacon', 'egg', 'ham', 'lobster', 'spam', 'tomato']
>>> a.sort(key=str.upper)
>>> a
['Apple', 'bacon', 'egg', 'ham', 'lobster', 'spam', 'tomato', 'Zebra']
>>> a.sort(key=str.upper, reverse=True)
>>> a
['Zebra', 'tomato', 'spam', 'lobster', 'ham', 'egg', 'bacon', 'Apple']


>>> b = [1, 77, 98, 34]
>>> b 
[1, 77, 98, 34]
>>> b.sort()
>>> b
[1, 34, 77, 98]
>>> b += ['apple']
>>> b
[1, 34, 77, 98, 'apple']
>>> b.sort()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    b.sort()
TypeError: '<' not supported between instances of 'str' and 'int'

.reverse() reverses the list in place:

>>>
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a.reverse()
>>> a
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']
>>> a.reverse()
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a = a[::-1]
>>> a
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']
Tuples

    A tuple is similar to a list except that it is fixed-length and immutable. So the values in the tuple cannot be changed nor the values be added to or removed from the tuple. Tuples are commonly used for small collections of values that will not need to change, such as an IP address and port. Tuples are represented with parentheses instead of square brackets:

ip_address = ('10.20.30.40', 8080)

The same indexing rules for lists also apply to tuples. Tuples can also be nested and the values can be any valid Python valid.

A tuple with only one member must be defined (note the comma) this way:

one_member_tuple = ('Only member',)
or
one_member_tuple = 'Only member', # No brackets
or just using tuple syntax

one_member_tuple = tuple(['Only member'])



Dictionaries:

A dictionary in Python is a collection of key-value pairs. The dictionary is surrounded by curly braces. Each pair is separated by a comma and the key and value are separated by a colon. Here is an example:

state_capitals = {

'Arkansas': 'Little Rock',
'Colorado': 'Denver',
'California': 'Sacramento',
'Georgia': 'Atlanta'

}


To get a value, refer to it by its key:

ca_capital = state_capitals['California']

You can also get all of the keys in a dictionary and then iterate over them:

for k in state_capitals.keys():

    print('{} is the capital of {}'.format(state_capitals[k], k))

Dictionaries strongly resemble JSON syntax. The native json module in the Python standard library can be used to convert between JSON and dictionaries.


Initialize an empty Dictionary

 d = {}


Add an element with key “­name” to the Dictionary

 d["name­"] = 'ram'{'name':'ram'}


Update the element with key “name”

d["name"] = 'tom'
d['age'] = 25{'name':'tom','age':25}


Get element with key “­k”

 d["name­"]'tom' -- If the key is not present, a KeyError is raised

Get the list of keys

 d.k­eys()

['name','age']

Get the size of the dictionary

 len(d) 

2




Set:

A set is a collection of elements with no repeats and without insertion order but sorted order. They are used in situations where it is only important that some things are grouped together, and not what order they were included. For large groups of data, it is much faster to check whether or not an element is in a set than it is to do the same for a list.

Defining a set is very similar to defining a dictionary:

first_names = {'Adam', 'Beth', 'Charlie'}

Or you can build a set using an existing list:

my_list = [1,2,3]
my_set = set(my_list)

Check membership of the set using in:

if name in first_names:
print(name)


Comments

Popular posts from this blog

Is-A and Has-A relationships in python

  In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House. #Is-A relationship --> By Inheritance class  A:    def   __init__ ( self ):      self .b= 10    def   mym1 ( self ):      print ( 'Parent method' ) class  B(A):    def   mym2 ( self ):      print ( 'Child method' ) d = B() d.mym1() #output: Parent method d.mym2() #output: Child method HAS-A Relationship:  Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom. Let’s understand...

Magic Methods in Python

  What Are Dunder Methods ? In Python, special methods are a set of predefined methods you can use to enrich your classes.  They are easy to recognize because they start and end with double underscores, for example  __init__  or  __str__ . Dunder methods let you emulate the behavior of built-in types.  For example, to get the length of a string you can call  len('string') . But an empty class definition doesn’t support this behavior out of the box: These “dunders” or “special methods” in Python are also sometimes called “magic methods.” class NoLenSupport : pass >>> obj = NoLenSupport () >>> len ( obj ) TypeError : "object of type 'NoLenSupport' has no len()" To fix this, you can add a  __len__  dunder method to your class: class LenSupport : def __len__ ( self ): return 42 >>> obj = LenSupport () >>> len ( obj ) 42 Object Initialization:  __init__ "__init __ ...

Inheritance and Types in Python

  Inheritance   Creating a new class from existing class is known as inheritance . The class from which features are inherited is known as base class and the class into which features are derived into is called derived class . Syntax: class  derived- class (base  class ):       < class -suite>      Inheritance promotes reusability of code by reusing already existing classes.  Inheritance is used to implement  is-a  relationship between classes.   Following hierarchy is an example representing inheritance between classes:   Single inheritance   When a derived class inherits only from syntax, the base class is called single inheritance. If it has one base class and one derived class it is called single inheritance.   Diagram     Syntax class  A:  #parent class         #some code       class  b(A):...