Data Structures in Python - Letsprogram

Share:
This post discusses some things you have learned about already in more detail and adds some new things as well.



Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple. List, the range is also the sequence data types. For data structures use sequence data types. Sets and dictionary are also sequence data types.

Lists

The list is a versatile data type and can be changed if you apply operations on it because the list is a mutable object.

Here are some methods of list-objects.

list.append(x)

Add an item to the end of a list. You can also add the element by 

>>> a[len(a):] = [x]

We discussed this kind of operation in the previous post of lists.

list.insert(i,x)

Adding an element x at i th position. i is the index of the list, list.insert(0,x) means inserting the element x at first place. list.insert(len(a),x) means same as list.append(x).

list.remove(x)

It will remove the first item with value x and raises the ValueError if there is no such value in the list.

list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.). The statement del can also pop the last element from the list.

>>>del a[len(a)]

list.clear()

Removes all the elements from the list. same as del a[:].The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). 

>>>del a[2:4]
>>>del a  #clears all the list

list.count(x)

Counts number of times x value is repeated in the list.

list.sort(key=None,reverse=False)

Sort the items of the list in place. There is a sorted() method that takes the list as an argument.

list.reverse()

Reverses the elements in the list.

list.copy()

Returns a shallow copy of the list. Equivalent to a[ : ]

You can use a list as stacks. It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of the list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue use collections.deque which was designed for fast appends and pops.



List Comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable or to create a subsequence of those elements that satisfy a certain condition.

>>>squares=[ ]
>>>for x in range(10):
            squares.append(x*x)
>>>squares
[0,1,4,9,16,25,36,49,64,81]

Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:

>>>squares=[x**2 for x in range(10) ]
or
>>>squares=list(map(lambda x : x**2 range(10)))

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses that follow it.


List Comprehensions can have complex expressions and nested functions. We can also use nested list comprehensions.

Tuples


As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however, it is possible to create tuples that contain mutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.

>>>empty = ( )

>>>singleton = 'Python',

>>>len(empty)

0

>>>len(singleton)

1

In above code, singleton tuple takes python value into it but observes there is a comma when defining the tuple.

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible

>>>x, y, z = t

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignments is really just a combination of tuple packing and sequence unpacking.

Sets

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the set() function can be used to create sets. Note: To create an empty set you have to use, not {};


Similarly to list comprehension, set comprehension is also possible.

Dictionary

Another useful data type built into Python is the dictionary. Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key: value pairs within the braces add initial key: value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key: value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.

Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.


dict() constructor is used to create a dictionary directly from key-value pairs. In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions. When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments

No comments

F