0% found this document useful (0 votes)
108 views10 pages

Python Data Structures

This document provides a summary of common Python data structures including lists, tuples, sets, and dictionaries. It describes the various methods available for lists, such as append(), insert(), remove(), and sort(). It also explains the differences between mutable lists and immutable tuples, as well as how to perform operations on sets like unions and intersections. Finally, it demonstrates how to use dictionaries to store and access data using unique keys.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views10 pages

Python Data Structures

This document provides a summary of common Python data structures including lists, tuples, sets, and dictionaries. It describes the various methods available for lists, such as append(), insert(), remove(), and sort(). It also explains the differences between mutable lists and immutable tuples, as well as how to perform operations on sets like unions and intersections. Finally, it demonstrates how to use dictionaries to store and access data using unique keys.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

PYTHON DATA

STRUCTURES

Python is one of the fastest growing programming languages in the


world. Almost all developers now use python, from web developers
to data scientist and other fields in programming. This ebook is a
summary of the data structures in python from the official python
documentation.
LISTS METHODS
The list data type has some more methods. Here are all of the methods of list objects:

list.append(x)
Add an item to the end of the list. Equivalent to a[len(a):] = [x].

list.extend(iterable )
Extend the list by appending all the items from the iterable. Equivalent
to a[len(a):] = iterable.

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element
before which to insert, so a.insert(0, x) inserts at the front of the list,
and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x)
Remove the first item from the list whose value is equal to x. It raises
a ValueError if there is no such item.

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.)

list.clear()
Remove all items from the list. Equivalent to del a[:].

list.index(x[, start[, end]])


Return zero-based index in the list of the first item whose value is equal to x.
Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and
are used to limit the search to a particular subsequence of the list. The returned
index is computed relative to the beginning of the full sequence rather than
the start argument.
list.count(x)
Return the number of times x appears in the list.

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


Sort the items of the list in place (the arguments can be used for sort
customization, see sorted() for their explanation).

list.reverse()
Reverse the elements of the list in place.

list.copy ()
Return a shallow copy of the list. Equivalent to a[:].

An example that uses most of the list methods:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple',


'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # Find next banana starting
aposition 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple',
'orange','grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi',
'orange','pear']
>>> fruits.pop()
'pear'
TUPLES AND SEQUENCES
The lists and strings have many common properties, such as indexing and slicing
operations. They are two examples of sequence data types (see Sequence Types —
list, tuple, range). Since Python is an evolving language, other sequence data types
may be added. There is also another standard sequence data type: the tuple.

A tuple consists of a number of values separated by commas, for instance:

>>>
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])

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, how ever it is
possible to create tuples which 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.
For example:

>>>
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

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 assignment 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 set(), not {}; the latter creates an empty dictionary, a data
structure that we discuss in the next section.

Here is a brief demonstration:

>>>
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange',
'banana'}
>>> print(basket) # show that duplicates have
been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate set operations on unique letters from two words


...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not
both
{'r', 'd', 'b', 'm', 'z', 'l'}

Similarly to list comprehensions, set comprehensions are also supported:

>>>
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

DICTIONARIES
Another useful data type built into Python is the dictionary (see Mapping Types — dict).
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 adds
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.
Here is a small example using a dictionary:

>>>
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

>>>
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}

In addition, dict comprehensions can be used to create dictionaries from arbitrary key
and value expressions:

>>>
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

When the keys are simple strings, it is sometimes easier to specify pairs using keyword
arguments:

>>>
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
Credit: Python Documentation.

You might also like