Basic data structures in Python

In this notebook we will take a look at few of the basic data structures available in Python

For the most part of your day to day work, you can get away with only these basic structures

Lists

  • Lists are an ordered sequence of values, for example: [10, 3, 4, 2]
  • Lists can contain any types of objects, for example ['apple', 10, 2.3, [1, 2]]

Creating an empty list


In [2]:
list1 = []
print list1


[]

Creating a list with some values


In [4]:
list2 = [10, 3, 4, 2]
print list2


[10, 3, 4, 2]

Creating list with different kinds of values


In [5]:
list3 = ['apple', 10, 2.3, [1, 2]]
print list3


['apple', 10, 2.3, [1, 2]]

Adding values to a list

List has a method append which adds a new item to the end of the list.


In [6]:
list1.append(5)
print list1
list1.append(3)
print list1
list1.append(8)
print list1


[5]
[5, 3]
[5, 3, 8]

Reading values from a list

Each item in the list has an index associated with it, starting from 0. We can use the square bracket ([]) notation with the index to access a specific item at the given index.


In [7]:
print list2


[10, 3, 4, 2]

In [8]:
print list2[0]
print list2[1]
print list2[2]
print list2[3]


10
3
4
2

Reading values from the end of a list

Just like the first element of the list is indexed at 0, the last element is indexed at -1, second last at -2 and so on


In [9]:
print list2


[10, 3, 4, 2]

In [10]:
print list2[-1]
print list2[-2]


2
4

Removing values from the list

Lists have a method pop() to remove item from a specific position in the list


In [11]:
print list2


[10, 3, 4, 2]

In [13]:
list2.pop(1) # Should remove value 3


Out[13]:
3

In [14]:
print list2


[10, 4, 2]

There is also a method remove which removes the first item with a given value in the list


In [15]:
list2.remove(4)
print list2


[10, 2]

Finding the length of the list

Python has a built in function len() which can be used to get the length of an object


In [18]:
print list2
print len(list2)


[10, 2]
2

Checking if a value exists in the list or not?

Python has the in operator to check whether an object contains a particular value or not.


In [19]:
print list3


['apple', 10, 2.3, [1, 2]]

In [20]:
'apple' in list3


Out[20]:
True

In [21]:
'orange' in list3


Out[21]:
False

Exercises:

  • Try and add two lists and see what happens
  • Try multiplying a list with an integer and see what happens
  • Try to implement a stack using the list
  • Try to implement a FIFO queue using the list

In [ ]: