Data structures consist of Strings, Lists, Tuples, Sets, and Dictionaries.
Lists
Lists have several methods:
list.append(x) to append an item to the end of a list
list.extend(iterable) to extend an entire list of items that are iterated over as opposed to appending one at a time.
list.insert(i , x) to insert an item into a list with i being the position in the list and x being the item to be entered.
list.remove(x) to remove all values x from the list
list.pop([i]) to remove an item from a list and return it. The square brackets are in place to denote that it is optional. When list.pop() is used without an item it removes the last item from a list.
list.clear() to remove all contents from a list
list.index(x[,start[, end]]) to return the index in the list that matches the item x. The search can have an index to start from or end at.
list.count(x) to count the number of occurrences of x in a list.
list.sort(key=None, reverse=False) to sort the items in a list
list.revers() to reverse the items in a list
list.copy() to copy the entire list
You can use the del statement to remove elements from a list using their index.
The example below deletes the first element in the list:
a = [ 1 , 2 , 3 , 4]
del a[0]
Tuples and Sequences
We already saw two examples of sequence types (string and list). Now we will look at a tuple. A Tuple consists of a number of values separated by commas.
For example:
t = 1, 2, 3, 4, ‘hello’
The output of a tuple is always enclosed in parenthesis so that is can be interpreted separately as a tuple. However, they can be inputted with or without parenthesis as with the example above.
Lists can be changed while tuples cannot. That said, tuples can be accessed by unpacking or indexing.
Sets
A set is an unordered collection with no duplicates. A set removes duplicates from entries and also support math operations like union, intersection, difference, and semantic difference.
for example:
a = {‘a’ , ‘z’ , ‘b’ , ‘z’}
print(a)
The output will be {‘a’, ‘z’, ‘b’}
The set() function can also be used to create a set. However, in this case you would not use a curly brace. You would just include the characters and the output will separate out all characters in that set.
Dictionaries
A dictionary is an unordered set of key value pairs with the requirement that the key be unique.
For example:
address = {‘John’: 123 Test, ‘Bob’: 456 North}
address[‘George’] = 847 South
The output of address is {‘John’: 123 Test, ‘Bob’: 456 North, ‘George’: 847 South}
The dict() function builds dictionaries directly from sequences of key valued pairs.
**This article is written for Python 3.6