Python Collection Data Types

What is collection data type

Collections in Python are containers that are used to store collections of data. There are a few modules have been developed that provide additional data structures to store collections of data. One such module is the Python collections module.

Collection Data Type: Lists, Tuples and Sets

Lists and Tuples are dealing with sequential data while Sets are for unordered values without duplication.

Lists

A list is an ordered collection of objects. You create a list by enclosing a comma-separated
list of elements in square brackets.

# This assigns a three-element list to x
x = [1, 2, 3, 4]

Python lists can contain different types of elements; a list element can be any Python object. Here’s a list that contains a variety of elements:

# First element is a number, second is a string, third is another list.
x = [2, "two", [1, 2, 3]]

The most basic built-in list function is the len function, which returns the
number of elements in a list (Note that the len function doesn’t count the items in the inner, nested list.):

x = [2, "two", [1, 2, 3]]
len(x) # returns 3

Access list item using index

Just like slicing string, list items can be accessed or sliced using index too.

courses = ['History', 'Math', 'Language', 'Science', 'Arts', 'Music']
print(courses[0])
print(courses[1])
print(courses[-1])
print(courses[0:3])
print(courses[2:])

results for above code are:

History
Math
Music
['History', 'Math', 'Language']
['Language', 'Science', 'Arts', 'Music']

Modifying lists

You can use list index notation to modify a list as well as to extract an element from it.

courses[0] = 'French'
courses

['French', 'Math', 'Language', 'Science', 'Arts', 'Music']

Method append()

Appending a single element to the end of a list.

courses.append('Chinese')
courses

['French', 'Math', 'Language', 'Science', 'Arts', 'Music', 'Chinese']

Method insert()

Insert new list elements between two existing elements or at the front of the list.

courses.insert(1, 'History')
courses

['French',
 'History',
 'Math',
 'Language',
 'Science',
 'Arts',
 'Music',
 'Chinese']

Function del()

Delete an item from the list with the given index.

del courses[1]
courses

['French', 'Math', 'Language', 'Science', 'Arts', 'Music', 'Chinese']

Method remove()

Method remove looks for the first instance of a given value in a list and removes that value from the list:

a = [1, 2, 3, 2, 4, 5]
a.remove(2)
print(a)
a.remove(2)
print(a)
a.remove(2)

[1, 3, 2, 4, 5]
[1, 3, 4, 5]
-----------------------------------------------------------------
ValueError       Traceback (most recent call last)
<ipython-input-81-6fd8af28d426> in <module>
      4 a.remove(2)
      5 print(a)
----> 6 a.remove(2)
ValueError: list.remove(x): x not in list

Sorting Lists

Lists can be sorted by using the built-in Python sort method

a = [3, 1, 6, 5, 4, 7, 2]
a.sort()
print(a)

[1, 2, 3, 4, 5, 6, 7]

Sorting works with strings, too:

courses.sort()
print(courses)

['Arts', 'Chinese', 'French', 'Language', 'Math', 'Music', 'Science']

Operator in with list

It’s easy to test whether a value is in a list by using the in operator, which returns a Boolean value. You can also use the converse, the not in operator:

3 in a # True
5 in courses # False
'Arts' in courses # True

Operator + with list

To create a list by concatenating two existing lists, use the + (list concatenation) operator, which leaves the argument lists unchanged

a = [1,2,3,4] + [2,3,4,5]
a

[1, 2, 3, 4, 2, 3, 4, 5]

Operator * for list initialing

Use the * operator to produce a list of a given size, which is initialized to a given value. This operation is a common one for working with large lists whose size is known ahead of time.

a = [0] * 10
a

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Function min() / max() for list

We can use min and max to find the smallest and largest elements in a list.

min([3,2,5,4,7,8]) # returns 2
max([55,23,87,19,356]) # returns 356

List matches with count

Method count also searches through a list, looking for a given value, but it returns the number of times that the value is found in the list.

a = [1, 2, 3, 4, 2, 3, 4]
a.count(2)

Summary of list operations
OperationNotesExample
[ ]Creates an empty lista = [ ]
lenReturns the length of a listlen(a)
appendAdds a single element to the end of a lista.append(b)
extendAdds another list to the end of the lista.extend([1,2])
insertInserts a new element at a given position in the lista.insert(2, 1)
delRemoves a list element or slicedel(a[1])
removeSearches for and removes a given value from a lista.remove(‘b’)
reverseReverses a list in placea.reverse()
sortSorts a list in placea.sort()
+Adds two lists togethera=[1,2] + [2,3]
*Replicates a lista = [0] * 5
minReturns the smallest element in a listmin(a)
maxReturns the largest element in a listmax(a)
indexReturns the position of a value in a lista.index(‘A’)
countCounts the number of times a value occurs in a lista.count(2)
sumSums the items (if they can be summed)sum(a)
inReturns whether an item is in a list2 in a

Tuples

Tuples are data structures that are very similar to lists, but they can’t be modified; they
can only be created.

Converting between lists and tuples

Tuples can be easily converted to lists with the list function. Similarly, lists can be converted to tuples with the tuple function.

list((1, 2, 3, 4))

[1, 2, 3, 4]

tuple([1, 2, 3, 4])

(1, 2, 3, 4)

Sets

A set in Python is an unordered collection of objects used when membership and uniqueness in the set are main things you need to know about that object. Data type like ints, floats, strings, and tuples can be members of a set, but collection types like lists, dictionaries, and sets themselves can’t.

s = { 5, 3, 6, 1, 3, 5, 6, 7}
s

{1, 3, 5, 6, 7}

s.add(8)
s

{1, 3, 5, 6, 7, 8}

s.remove(5)
s

{1, 3, 6, 7, 8}