DEV Community

loading...

Difference among list, tuple and set in Python and when to use each one

Flávia Bastos
Professional learner
Originally published at flaviabastos.ca on ・2 min read

Python has three similar data structures that can hold an unordered collection of elements: list, tuple and set.

Here’s how they differ:

initialization

list : using the built-in list() or the square brackets ([]):

list1 = list() # creates an empty listlist2 = [] # also creates an empty listlist3 = ['a', 'b', 'c', 4]

tuple: elements separated by comma:

t = 'one', 'two', 'three', 4

set : using the built-in set() or curly braces ({}):

set1 = set() # creates an empty setset2 = {'one', 'two', 'three', 4}

access

Access list and tuple elements using their index:

>>> list3[0]'a'>>> t[0]'one'

A set cannot be accessed via index:

>>> set2[0]Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'set' object does not support indexing

mutability

A list is mutable:

>>> list3[0] = 1>>> list3[1, 'b', 'c', 4]

A tuple is immutable:

>>> t[0] = 1Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment

set s are also immutable since you cannot access its elements through index.

basic usage

list : used to store a collection of homogeneous data that can be mutated (but can also be used to store heterogeneous data as in my list3 example above!). list is very versatile and implements all common and mutable sequence operators. They can also be used as stacks and queues.

tuple: used to store a collection of heterogeneous data, like in my example t above, or to store homogeneous data that cannot be mutated. They are used to create the output of the enumerate() built-in:

>>> doggos = ['labrador', 'german shepherd', 'poodle'] # regular list>>> list(enumerate(doggos))[(0, 'labrador'), (1, 'german shepherd'), (2, 'poodle')] # list of tuples, where the first element in the tuple is the index# and the second is the value from the list

I wrote more about using enumerate() to map a string here.

set: used to eliminate duplicate elements and for membership testing:

>>> 4 in set3 # membership testingTrue>>> set4 = set('banana') # eliminate duplicates>>> set4{'a', 'b', 'n'}>>> set5 = {'one', 'two', 'three', 'one', 'three'} >>> set5{'three', 'one', 'two'}>>> set6 = set(['one', 'two', 'three', 'two', 'one'])>>> set6{'three', 'one', 'two'}

The post Difference among list, tuple and set in Python and when to use each one_ was originally published on _flaviabastos.ca

Discussion (0)