Python Collections

Python has 4 different types of data collections.

  • List
  • Tuple
  • Dictionary
  • Set

The following section describes all 4 collections data type and various operation on it with examples.

List

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values between square brackets. Python List allows duplicate values. An index number is used to access a particular list element.

Create a list

li = ['a','b','c','d']

Python also supports negative indexing means -1 refer to the last elements of the list, -2 refers to the second last elements of the list. You can also access the range of list elements by defining the first and last index of the range.

Tuple

A Tuple is the collection of immutable Python objects. Tuples are sequences, just like lists.  But, the main difference between list and tuple is, Tuple is immutable means it isn’t allowed to change value. A tuple is written in round brackets. An index number is used to access a particular Tuple element like List.

Create a tuple

li = ('a','b','c','d')

Dictionary

A dictionary is key-value pair datatype written in curly brackets. Dictionary is unordered and changeable. Keys must be unique in the dictionary but the value may not be. You can access the dictionary value by its key.

dict = {'fruit':'apple','color':'yellow','shape':'circle','quantity':50}

Set

A set is Python’s collection which is unindexed and unordered. A set is written as a sequence of comma-separated values between {} curly brackets. Like tuple, the set is also immutable means you are not allowed to change the set elements. A set doesn’t contain any duplicate items.

Set can also be used to calculate the mathematical set operations such as union, intersection, difference, symmetric difference, etc.

set1 = {"green", "red", "blue" ,"blue"}
print(set1)

# Output
{'red', 'blue', 'green'}   # It discard the duplicate elements.

.     .     .

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Tutorials

Python – List Comprehension

Python Set

Python : Assert Keyword

Python Dictionary

Python Tuple

Python List

Python: String

Python: String Formatting using f-string

Python: String Formatting – 2

Python: String Formatting – 1

Python Input/Output

Python Type Conversion and Type Casting

Python Comments

Python – Regular Expression (RegEx)

Python Iterators

Python File Handling

Python Exceptions

Python Function

Python Loops

Python If…Else

Python Operators

Variables in Python

Python Syntax

Introduction to Python

Python OOPs Concepts

Study Machine Learning