top of page
  • Writer's pictureHarini Mallawaarachchi

Python Collections

Python has built-in Collections which are used to store data, for example, lists, dictionaries, sets, and tuples, all of which are built-in collections.


The following are the differences between each of these collections.

Lists

Tuples

Sets

Dictionaries

Ordered

Yes

by index

Yes

by index

No

Yes

by key

Allow duplicates

Yes

Yes

No

Yes

Mutable

Yes

No

Yes

Yes

Slicing

Yes

Yes

No

No

Change of element

Yes

No

No

Yes

Represented by

[ ]

( )

( )

{ }

example

[1, 2, 3, 'four', 5]

​('gfg', 1, ['is', 'best'])

{1, 2, 3, 4, 5}

{1:"a", 2:"b", 3:"c"}

The above-mentioned collections have different actions.

Let's go through each of them.


Lists

Tuples

Sets

Dictionaries

Initiate


l = []


t = ()


a = set()


d = {}

Add


l.append(2)


s.add(2)


d[0] = "One"

Remove


l.pop()


s.remove(2)


del d[0]

Let's see the time complexity of each of these collections.

List

Tuple

Set

Dictionary

Addition

O(1)

-

O(1)

O(1)

Deletion

O(n)

-

O(1)

O(1)

Access by index

O(1)

O(1)

-

O(1)

Check inclusion

O(n)

O(n)

O(1)

O(1)

Get length

O(1)

O(1)

O(1)

O(1)


As a summary let's see which is best to use and where.

List

Tuple

Set

Dictionary

  • Used in JSON format.

  • Useful for Array operations.

  • Used in Databases.

  • Used to insert records in the database through SQL query at a time.

  • Used in parentheses checker.

  • More memory & time efficient compared to list.

  • Can have various data types.

  • Finding unique elements

  • Join operations

  • Used to create a data frame with lists

  • Used in JSON








3 views0 comments

Recent Posts

See All

Comentários


bottom of page