Collection Data Types in Python

Enoch Lamikanra
Analytics Vidhya
Published in
4 min readFeb 12, 2021

--

Photo by Shahadat Rahman on Unsplash

Python has 4 built-in data structures that can be used to hold a collection of objects, they are list, tuple, set, and dictionary. They can be distinguished into mutable, immutable, set type, and mappings respectively.

Lists

Lists are ordered mutable sequences that can be changed after they have been created by adding, removing, or changing objects. Lists can be declared by using square brackets “[]” following the variable name.

Tuples

Tuples are ordered immutable sequence that stores multiple items in a single variable, meaning it cannot be changed after it has been created. A tuple can be created by a pair of parenthesis and comma-separated objects, following the variable name.

Single object tuples are referred to as a singleton. It can be created by using a trailing comma after the object, or else python identifies it as a string.

Commas are what makes a tuple, as parentheses are optional.

Sets

Sets are an unordered immutable set of unique objects that do not support duplicated objects and as such, they cannot be indexed. Mathematical operations such as intersection, union, difference, and symmetric difference, can be carried out on set data types. Sets can be created by using curly brackets following the variable names or using the set() constructor.

Similarities between lists, tuples, and sets

  1. They support any data type

2. Lists and tuple allow duplicate elements

3. List and set are mutable i.e. changes can be made after creating them

4. List and tuple are ordered sequences

Differences between lists, tuples, and sets

  1. Whilst lists and sets are mutable, tuples are immutable i.e. no changes can be made after a tuple has been created, as python will return an attribute error which indicates that the method or operation is not possible on that object.

2. Sets are unordered and can appear in a different order every time you use them, and cannot be referred to by index or key.

3. List and tuples accept duplicate items, while set simply takes one of the duplicate objects.

Dictionary

A dictionary is an unordered set of key/value pairs. Each unique key has a value
associated with it in the dictionary, and dictionaries can have any number of
pairs. The values associated with a key can be any object. LIke sets, dictionaries are unordered.

Values in dictionary items can be of any data type.

Ditionaries are mutable, this allows items to be added or removed even after the dictionary has been created. However, duplicates are not allowed, as a dictionary cannot have multiple items with the same key, because the values will overwrite and the most recent value will be returned.

--

--