Data structures in Python

List

There are some inbuilt functions which makes the job easier. Using list we can modify the data in any order.

a.append(“Value”) is the general syntax which is used to add value in the list at the last position.For example we shall create a list,

>>>a = [1,2,3,4,5]

When we give – a.append(6), it will show the output as

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

To remove a element in list at last and to return its value, a.pop() command is used. When a.pop() given,it will show the output as

6

To remove the first element in the list, a.pop(0) is given,

1

To insert the element in list, a.insert(“Position”, “Value”). When a.insert(0,5) is given,

>>>[5,2,3,4,5]

To delete the element in the list, a.remove(“Key”) is used. a.remove(3) will give the output as

[5,2,4,5]

To reverse the element, a.reverse() is used.

[5,4,2,5]

To count the number of element in the list, a.count() is used.

4

In case if we want to join two lists, then the keyword extend is used. The syntax is a.extend(b)

>>>b = [6,7,8]

>>>a.extend(b)

[5,4,2,5,6,7,8]

Introduction to Set

Set is used when we have several duplicate values. I removes the duplicate value and displays only the original value. We can also perform some mathematical operations. Set can be created by using a keyword set.

>>>a = set(“abcdabcdef”)

{‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’}

>>>a

To perform mathematical operation,

>>>a = set(“abcd”)

>>>b = set(“cdef”(

>>>a – b

{‘a’ , ‘b’}

>>>a | b

{‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’}

>>>a & b

{‘c’, ‘d’}

To add a element in the set, add keyword is used.

>>>a.add(‘g’)

{‘a’, ‘b’, ‘c’, ‘d’, ‘g}

Leave a comment