Python Data Structures 📚

Photo by Joshua Sortino on Unsplash

Data structures

Data structures allows you to organize data in your programs. Some of the operations like reversing a string are made to be so easy in python with single line code. Lets see some of the data structures and their operations,

  • Lists
  • Tuples
  • Dictionaries
  • Set
  • Sequence

List

A list can be created as follows -

listname = [element1, element2, element3, element4, element5]

Examples-

number_list = [1,5,8,9,3]
input_data = ["Python","Java"]

If we want to print the list using print statement, output would be in the form of a list again.

Example,

print(number_list)

Output,

[1, 5, 8, 9, 3]

In order to print list elements separately , means not in a list, we can do this by using a for loop as follows,

for i in range(0,5):
print(number_list[i])

output is as ,

1
5
8
9
3

lets see some of the list Operations,

  • Length of a List
  • List Indexing
  • Negative Indexing
  • List Slicing
  • Creating a shallow copy of a list
  • Appending values to Lists
  • Concatenating Lists
  • Assigning elements to Lists
  • Removing elements from Lists
  • Popping Out elements in a list
  • Emptying a List
  • Remove First element from List
  • Inserting elements to Lists
  • Count in a List
  • Reversing a List
  • Sorting Lists
  • List comprehensions
  • Using Lists as stacks
  • Using Lists as Queues
  • Nesting two Lists

Length of a List

len(list_name)

Example,

len(number_list)

List Indexing

print(number_list[0])

Output for this will be 1, as index of first element in number_list is 1.

We can expect an Index Error whenever we try to attempt to access an index that is outside the bounds of a list.

Here lets try to print an element which is out of bound, using print(number_list[5]) as index value of number_list ends at 4.

Traceback (most recent call last):
print(number_list[5])
IndexError: list index out of range

Negative Indexing

Index value of -1 gives the last element of list, and -2 gives the second last element of the list.

Example 1,

print(number_list[-1])

This prints the list value 3.

Example 2,

print(number_list[-3])

This prints the list value 8.

List Slicing

Photo by Yair Mejía on Unsplash

We can get elements from one given index to another given index in Python using slicing.

It can be done by passing slice instead of index.

[start:end] .

Can also define the step, using [start:end:step] .

If we don’t specify starting slice number , default number as Zero is considered.

If we don’t pass end its considered length of array in that dimension.

Like strings and all other built-in sequence types , lists can be indexed and sliced.

Slicing a list returns a new list.

Example,

print(number_list[-1])

Output,

3

Creating a shallow copy of a list

Syntax,

list_name[:]

Example,

print(number_list[:])

Output,

[1, 5, 8, 9, 3]

using copy() method,

number_list.copy()

Appending values to Lists

number_list.append(10)
print(number_list)

Output,

[1, 5, 8, 9, 3, 10]

Concatenating Lists

Example,

print(number_list + [20,30])

Output list,

[1, 5, 8, 9, 3, 10, 20, 30]

Assigning elements to Lists

Example,

number_list[5:8] = [50,40,70]
print(number_list)

Here, we are trying to add 3 elements, 50,40,70 to number_list . So last three elements are replaced. Output would be like,

[1, 5, 8, 9, 3, 50, 40, 70]

Removing elements from Lists

number_list[5:8] = []
print(number_list)

Output list would be,

[1, 5, 8, 9, 3]

Popping Out elements in a list

If no index is specified inside pop() method, removes and returns the last item in the list. Example,

number_list.pop()

Emptying a List

list_name[:] = []list_name.clear()

Remove First element from List

list_name.remove()

Inserting elements to Lists

The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

number_list.insert()

Count in Lists

list_name.count(element)

for example if we have a list as [1, 5,2, 8, 9, 3, 2, 4, 2,5] and if we try to get the count of number 2 that appeared in this list,

print(number_list.count(2))

output would be 3 as number 2 appeared three times in the above list.

Reversing a List

list_name.reverse()

example,

number_list.reverse()
print(number_list)

here our list is [1, 5, 8, 9, 3, 2, 4, 5] and once it is reversed , the list we get is [5, 4, 2, 3, 9, 8, 5, 1]

Sorting Lists

example,

text = ['abc','bcd','xyz']
text.sort()
print("Sorted list - " ,text)

output,

Sorted list -  ['abc', 'bcd', 'xyz']

to reverse a sorted list, pass “reverse=True” as argument in sort() method.

text.sort(reverse=True)

output is,

Sorted list — [‘xyz’, ‘bcd’, ‘abc’]

Using Lists as stacks

Using Lists as Queues

Nesting two Lists

a = [1,2,3]b=[4,5,6]c=[a,b]print(c)

output,

[[1, 2, 3], [4, 5, 6]]

Here in this example, while accessing indexes c[0] will print the whole “a” list and c[1] prints “b” list.

print("Index 0 - a list " , c[0])
print("Index 1 - b list " ,c[1])

output ,

Index 0 — a list [1, 2, 3]
Index 1 — b list [4, 5, 6]

If want to access specific item in this list,

print(c[0][1])

returns first item of first list in a nested list. Here, result is 1.

Will continue the other data structures in next upcoming blog. Stay tuned.

Thanks for reading…

Software Engineer