Inbuilt Data Structures in Python (original) (raw)

Last Updated : 08 Aug, 2022

Python has four non-primitive inbuilt data structures namely Lists, Dictionary, Tuple and Set. These almost cover 80% of the our real world data structures. This article will cover the above mentioned topics.

Above mentioned topics are divided into four sections below.

Lists: Lists in Python are one of the most versatile collection object types available. The other two types are dictionaries and tuples, but they are really more like variations of lists.

Dictionary: In python, dictionary is similar to hash or maps in other languages. It consists of key value pairs. The value can be accessed by unique key in the dictionary.

Syntax:

dictionary = {"key name": value}

Tuple : Python tuples work exactly like Python lists except they are immutable, i.e. they can’t be
changed in place. They are normally written inside parentheses to distinguish them from lists (which use square brackets), but as you’ll see, parentheses aren’t always necessary. Since tuples are immutable, their length is fixed. To grow or shrink a tuple, a new tuple must be created.

Here’s a list of commonly used tuples:

() An empty tuple t1 = (0, ) A one-item tuple (not an expression) t2 = (0, 1, 2, 3) A four-item tuple t3 = 0, 1, 2, 3 Another four-item tuple (same as prior line, just minus the parenthesis) t3 = (‘abc’, (‘def’, ‘ghi’)) Nested tuples t1[n], t3[n][j] Index t1[i:j], Slice len(tl) Length

Python3

tup = ( 1 , "a" , "string" , 1 + 2 )

print (tup)

print (tup[ 1 ])

Output:

(1, 'a', 'string', 3) a

Detailed article on Tuples in Python

Sets: Unordered collection of unique objects.

Python3

set1 = set ()

set2 = set ()

for i in range ( 1 , 6 ):

`` set1.add(i)

for i in range ( 3 , 8 ):

`` set2.add(i)

print ( "Set1 = " , set1)

print ( "Set2 = " , set2)

print ( "\n" )

Output:

('Set1 = ', set([1, 2, 3, 4, 5])) ('Set2 = ', set([3, 4, 5, 6, 7]))

To read more about sets in python read our article about set by clicking here.