Python Data Structures Tutorial For Beginners 2020

Python Data Structures Tutorial For Beginners 2020. Here in this blog post Coding compiler sharing Python 3 programming data structures tutorial for beginners. You will learn about list, dict, tuples, sets, strings and other Python data structures. This Python tutorial is for absolute beginners who are looking for learning Python programming. Let’s start learning Python 3.

Python Data Structures

This chapter we will discusses in detail on Python data structures like list, dict, tuples, sets, strings and some of the topics you have already learned and also adds some new Python topics.

Related Articles: Python Getting Started Guide  |  Introduction to Python

1. Python list

Python’s list data type contains more methods. Here is all the list object methods:

list.append)
Adding an element to the end of the list is equivalent .a[len(a):] = [x]
list.extend)
Adding all the elements in a given list to another list is equivalent .a[len(a):] = L
list.inserti , )
Insert an element at the specified position. The first parameter is ready to be inserted into the front of its index of that element, for example, is inserted into the entire list before, and equivalent .a.insert(0, x)a.insert(len(a), x)a.append(x)
list.remove)
Deletes the first element in the list with the value x . If there is no such element, an error will be returned.
list.pop[])
Removes the element from the specified position of the list and returns it. If no index is specified, the a.pop()last element is returned. The element is then removed from the list ( the square brackets around the i in the method indicate that this parameter is optional, rather than asking you to type in a square bracket. You will often see this in the Python Library Reference Manual).
list.clear)
Remove all elements from the list. Equivalent .del a[:]
list.index)
Returns the index of the first element in the list whose value is x . If there is no matching element it will return an error.
list.count)
Returns the number of occurrences of x in the list.
list.sort)
Sorts the elements in the list in place.
list.reverse)
Invert the list of elements in the list.
list.copy)
Returns a shallow copy of the list. Equivalent to a[:].

The following example demonstrates most of the methods of the list:

>>> a  =  [ 66.25 ,  333 ,  333 ,  1 ,  1234.5 ] 
>>> print ( a . count ( 333 ),  a . count ( 66.25 ),  a . count ( 'x' )) 
2 1 0 
>>> a . insert ( 2 ,  - 1 ) 
>>> a . append ( 333 ) 
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333] 
>>> a . index ( 333 ) 
1 
>>> a . remove ( 333 ) 
>>> a 
[66.25, -1, 333, 1, 1234.5 , 333] 
>>> a . reverse () 
>>> a 
[333, 1234.5, 1, 333, -1, 66.25] 
>>> a . sort () 
>>> a 
[-1, 1, 66.25, 333 , 333, 1234.5] 
>>> a . pop () 
1234.5 
>>> a 
[-1, 1, 66.25, 333, 333]

Perhaps you will find like insertremoveor sortthese methods modify the list does not print the return value – they return None[1] This is a unified design principle for all mutable data types in python.

Related Article: Python Interpreter Tutorial

1.1. Using a List as a Stack

The list method makes it convenient to use a list as a stack. The stack is used as a specific data structure. The last element that is entered is released (last in, first out). Use append()can add an item to the top of the stack. The index is not specified by pop()method of an element can be released from the top of the stack. E.g:

>>> stack  =  [ 3 ,  4 ,  5 ] 
>>> stack . append ( 6 ) 
>>> stack . append ( 7 ) 
>>> stack 
[3, 4, 5, 6, 7] 
>>> stack . Pop () 
7 
>>> stack 
[3, 4, 5, 6] 
>>> stack . pop () 
6 
>>> stack . pop () 
5 
>>> stack 
[3, 4]

1.2. Using Lists as Queues

You can also use the list as a queue. As a specific data structure, the queue is the first to be released (first in, first out). However, the list is inefficient. Relatively speaking, adding and popping from the end of the list is very fast; inserting and popping at the head is slow (because, for an element, all the elements in the entire list are moved).

To implement the queue, use collections.deque , which is designed for quick insertion and deletion at both ends. E.g:

>>> from  collections  import  deque 
>>> queue  =  deque ([ "Eric" ,  "John" ,  "Michael" ]) 
>>> queue . append ( "Terry" )            # Terry arrives 
>>> queue . append ( " Graham" )           # Graham arrives 
>>> queue . popleft ()                  # The first to arrive now leaves 
'Eric' 
>>> queue .Popleft ()                  # The second to arrive now leaves
'John' 
>>> queue                            # Remaining queue in order of arrival 
deque(['Michael', 'Terry', 'Graham'])

Related Articles: Learn Python In One Day

1.3. List Derivation

List comprehensions provide a simple way to create a list from a sequence. An ordinary application creates a subsequence by applying some operations to each member of the sequence and creating a list through the returned elements, or by elements that satisfy certain conditions.

For example, suppose we create a squares list that can look like this:

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

Note that the for loop is created (or rewrite) named xvariables still exist after the cycle is complete. Using the following method, we can calculate the value of squares without any side effects:

Squares  =  list ( map ( lambda  x :  x ** 2 ,  range ( 10 )))

Or, equivalent to:

Squares  =  [ x ** 2  for  x  in  range ( 10 ]]

The above method is more concise and easy to read.

List comprehensions consist of parentheses that contain an expression followed by a for clause and can have zero or more for or if clauses. The result is a list consisting of the expression ‘s results computed from the context of the for and if clauses that follow it.

For example, the following list derivation combines the elements of two lists if the elements are not equal:

>>> [( x ,  y )  for  x  in  [ 1 , 2 , 3 ]  for  y  in  [ 3 , 1 , 4 ]  if  x  !=  y ] 
[(1, 3), (1, 4), (2 , 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Equivalent to:

>>> combs  =  [] 
>>> for  x  in  [ 1 , 2 , 3 ]: 
...     for  y  in  [ 3 , 1 , 4 ]: 
...         if  x  !=  y : 
...             combs . append (( x ,  y )) 
... 
>>> combs 
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1) , (3, 4)]

It is worth noting the order of the for and if statements in the above two methods .

If you want to get a tuple (for example, in the above example ), you must add parentheses:(x, y)

>>> vec  =  [ - 4 ,  - 2 ,  0 ,  2 ,  4 ] 
>>> # create a new list with the values ​​doubled 
>>> [ x * 2  for  x  in  vec ] 
[-8, -4, 0 , 4, 8] 
>>> # filter the list to exclude negative numbers 
>>> [ x  for  x  in  vec  if  x  >=  0 ] 
[0, 2, 4] 
>>> # apply a function to all the elements 
> >>[Abs ( x )  for  x  in  vec ] 
[4, 2, 0, 2, 4] 
>>> # call a method on each element 
>>> freshfruit  =  [ ' banana' ,  ' loganberry ' ,  'passion fruit ' ] 
> >> [ weapon . strip ()  for  weapon  in  freshfruit ] 
['banana', 'loganberry', 'passion fruit'] 
>>> # create a list of 2-tuples like (number, square) 
>>> [( x , x ** 2 ) For  x  in  range ( 6 )] 
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] 
>>> # the Tuple must be parenthesized, otherwise an error is raised 
>>> [ x ,  x ** 2  for  x  in  range ( 6 )] 
  File "<stdin>", line 1, in ? 
    [x, x**2 for x in Range(6)] 
               ^ 
SyntaxError: invalid syntax 
>>> # flatten a list using a listcomp with two 'for' 
>>> vec  =  [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ],  [ 7 , 8 , 9 ]] 
>>> [ num  for  elem  in  vec  for  num  in  elem ] 
[1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehensions can use complex expressions and nested functions:

>>> from  math  import  pi 
>>> [ str ( round ( pi ,  i ))  for  i  in  range ( 1 ,  6 )] 
['3.1', '3.14', '3.142', '3.1416', '3.14159' ]

Related Article: Python For Machine Learning

1.4. Nested List Derivation

The first expression in list parsing can be any expression, including list comprehensions.

Consider the following 3×4 matrix consisting of three lists of length 4:

>>> matrix  =  [ 
...     [ 1 ,  2 ,  3 ,  4 ], 
...     [ 5 ,  6 ,  7 ,  8 ], 
...     [ 9 ,  10 ,  11 ,  12 ], 
... ]

Now, if you want to swap rows and columns, you can use nested list comprehensions:

>>> [[ row [ i ]  for  row  in  matrix ]  for  i  in  range ( 4 )] 
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

As seen earlier, the nested list formula is derived for the back of the contents is evaluated, so the embodiment is equivalent to:

>>> transposed  =  [] 
>>> for  i  in  range ( 4 ): 
...     transposed . append ([ row [ i ]  for  row  in  matrix )) 
... 
>>> transposed 
[[1, 5, 9 ], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Conversely, the following is the same:

>>> transposed  =  [] 
>>> for  i  in  range ( 4 ): 
...     # # the following 3 lines implement the nested listcomp 
...     transposed_row  =  [] 
...     for  row  in  matrix : 
...         transposed_row . Append ( row [ i ]) 
...     transposed . append ( transposed_row ) 
... 
>>> transposed 
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4 , 8, 12]]

In practice, you should prefer to use built-in functions to compose complex process statements. The zip() function will do better for this case :

>>> list ( zip ( * matrix )) 
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

2. The del statement

There is a way to delete a subkey from a list with a given index instead of a value: the del statement. It returns a value different from the pop()method. The statement del can also remove slices from the list or empty the entire list (one of the methods we’ve previously described is assigning an empty list to a slice of a list). E.g:

>>> A  =  [ - . 1 ,  . 1 ,  66.25 ,  333 ,  333 ,  1234.5 ] 
>>> del  A [ 0 ] 
>>> A 
[. 1, 66.25, 333, 333, 1234.5] 
>>> del  A [ 2 : 4 ] 
>>> a 
[1, 66.25, 1234.5] 
>>> del  a [:] 
>>> a 
[]

Del can also delete the entire variable:

>>> del  a

Referencing name awill cause an error (until another value is assigned to it so far). We can see other usages of del in the following content .

3. Tuples and Sequences

We know that lists and strings have many common properties, such as indexing and cutting operations. They are sequence types (see Sequence Types – List, tuple, Range ) in two kinds. Since Python is a constantly evolving language, other sequence types may also be added. Here is another standard sequence type: tuples .

A tuple consists of several comma-separated values, for example:

>>> 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 can see, tuples are always parenthesized when they are output, so that they can be expressed correctly. You can have or without parentheses when typing, but often parentheses are required (if the tuple is part of a larger expression).

You can’t assign a single element to a tuple (although you can simulate it with joins and cuts). You can also create tuples that contain mutable objects, such as lists.

Although tuples and lists are very similar, they are often used in different situations and for different purposes. Tuples have many uses. Examples are (x, y) coordinate pairs, employee records in the database, and so on. Tuples are like strings and immutable .

It usually contains different kinds of elements and is accessed by splitting (see later in this section) or indexing (if it is named tuples , it can even pass attributes). The list is variable , their elements are generally the same type of access and iterative.

A special problem is to construct a tuple containing zero or one element: In order to adapt to this situation, there are some additional changes in the syntax. An empty pair of parentheses can create an empty tuple; to create a single unit tuple can be followed by a comma (with a single value in parentheses is not clear enough). Ugly but effective. E.g:

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

Statement is a tuple packing an example (tuple packing): the values , and are encapsulated into tuples. Its inverse operation may be this:t = 12345, 54321, 'hello!'1234554321'hello!'

>>> x ,  y ,  z  =  t

This call to the right of the equal sign can be any linear sequence, called the sequence unpacking very appropriate. Sequence unpacking requires that the number of variables on the left be the same as the number of elements in the sequence. It should be noted that multiple assignments are simply a combination of tuple encapsulation and sequence unpacking.

4. Collection

Python also contains a data type – set . A collection is a set of unordered, non-repeating elements. Basic features include relationship testing and eliminating duplicate elements. Collection objects also support mathematical operations such as union, intersection, difference, and sysmmetric difference.

Braces or set() functions can be used to create collections. Note: If you want to create an empty set, you have to use set()instead {}. The latter is used to create an empty dictionary, a data structure we introduced in the next section.

The following is a simple demo:

>>> 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 either a or b 
{'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'}

Similar list of comprehension , here there is a set of derivation grammar:

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

5. Dictionary

Another useful data type built into Python is the dictionary (see Mapping Types – dict ). Dictionaries may be called associative memories or associative arrays in some languages. Sequences, which are integer indexes, and this difference is that, in the dictionary keyword index, keywords can be any immutable type, usually a string or numeric.

If the tuple contains only strings and numbers, it can be used as a keyword. If it contains a variable object directly or indirectly, it cannot be used as a key. Do not use keyword list, because the list can use the index, or cut append()and extend()change methods.

The best way to understand a dictionary is to think of it as an unordered key: a set of value pairs(key:value pairs). The keys must be different (in the same dictionary). Create an empty dictionary with a pair of braces: {}. When the list is initialized, a set of comma-separated keys are placed in braces: a value pair, which is how the dictionary is output.

The main operation of the dictionary is to store and extract values based on keys. It can also be used delto delete a key: value pair (key: value). If you store a value with an existing keyword, the previously assigned value for that keyword is forgotten. Attempting to take a value from a non-existent key will result in an error.

The implementation of a dictionary list(d.keys())returns a dictionary unordered list of all the keys (if you want to sort, just use in keywords (refer to Python syntax) can check whether there is a keyword dictionary (refers to the dictionary).sorted(d.keys()) 

Here is a small example of using a dictionary:

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

The dict() constructor can create a dictionary directly from a key-value pair:

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

In addition, dictionary derivation can create a dictionary from any key-value expression:

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

If the keywords are simple strings, it is sometimes more convenient to specify key-value pairs with keyword arguments:

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

6. Cycling Skills

When circulating in the dictionary, and the corresponding keyword values can be items()Simultaneous deciphered:

>>> knights  =  { 'gallahad' :  'the pure' ,  'robin' :  'the brave' } 
>>> for  k ,  v  in  knights . items (): 
...     print ( k ,  v ) 
... 
Gallahad the pure 
robin the brave

When looping through the sequence, the index position and corresponding values can be obtained simultaneously using the enumerate() function:

>>> for  i ,  v  in  enumerate ([ 'tic' ,  'tac' ,  'toe' ]): 
...     print ( i ,  v ) 
... 
0 tic 
1 tac 
2 toe

While looping two or more sequences, you can use zip() as a whole to pack:

>>> questions  =  [ 'name' ,  'quest' ,  'favorite color' ] 
>>> answers  =  [ 'lancelot' ,  'the holy grail' ,  'blue' ] 
>>> for  q ,  a  in  zip ( questions ,  answers ): 
...     print ( 'What is your {0} ? It is {1} .' . format ( q ,  a )) 
...
What is your name? It is lancelot.
What is your quest? It is the holy grail. 
What is your favorite color? It is blue.

If you need to reverse the loop sequence, first position the sequence forward and call the reversed()function:

>>> for  i  in  reversed ( range ( 1 ,  10 ,  2 )): 
...     print ( i ) 
... 
9 
7 
5 
3 
1

To loop through the sequence in sorted order, use the sorted() function, which does not alter the original sequence, but instead generates a new sorted sequence:

>>> basket  =  [ 'apple' ,  'orange' ,  'apple' ,  'pear' ,  'orange' ,  'banana' ] 
>>> for  f  in  sorted ( set ( basket )): 
...     print ( f ) 
... 
apple 
banana 
orange 
pear

To modify a sequence that is being traversed inside a loop (such as copying some elements), we recommend that you make a copy first. Cycling on a sequence does not implicitly create a copy. Slice representation makes this particularly convenient:

>>> words  =  [ 'cat' ,  'window' ,  'defenestrate' ] 
>>> for  w  in  words [:]:   # Loop over a slice copy of the entire list. 
...     if  len ( w )  >  6 : 
...         words . insert ( 0 ,  w ) 
... 
>>> words 
['defenestrate', 'cat', 'window', 'defenestrate']

7. In-depth condition control

whileAnd ifconditional statements may be used not only for use in comparison, but can contain any of the operations.

The comparison operators inand auditing value is within a range of. Operators and whether two objects are the same the comparison; and only such lists as mutable objects. All comparison operators have the same priority and operate below all numeric values.not inisis not

Comparison operations can be passed. For example tests whether less than and equal to .a < b == cabbc

Comparison operation by logical operators andand orcombined, compared, the results can notbe negated. Priority of these operators is lower than the comparison operators and, among them, nothave the highest priority, orthe lowest priority, so equal . Of course, parentheses can also be used to compare expressions.A and not B or C(A and (notB)) or C

Logical operators andand oralso referred to as short-circuit operators: their parameters parsed from left to right, the result may be determined once stopped.

For example, if Aand Cas true and Bfalse, it does not resolve . When acting on an ordinary non-logical value, the return value of the short-circuit operator is usually the last variable.A and B and CC

You can assign the return value of a comparison or other logical expression to a variable, for example:

>>> string1 ,  string2 ,  string3  =  '' ,  'Trondheim' ,  'Hammer Dance' 
>>> non_null  =  string1  or  string2  or  string3 
>>> non_null 
'Trondheim'

Note that Python is different from C in that it cannot be assigned inside an expression. C programmers may grumble about this, but it avoids a common class of errors in C programs: in an expression you want to ==misuse the =operator.

8. Comparing Sequences and Other Types

Sequence objects can be compared to other objects of the same type. Compare proceed as lexicographical : firstly compare the first two elements, if different, determines the result of the comparison; if the same, then compare the two elements, and so on, until all are completed sequence comparison.

If two elements are themselves sequences of the same type, recursive lexicographical comparisons. If all the children of two sequences are equal, the sequences are considered equal.

If one sequence is the initial subsequence of another sequence, the shorter one is smaller than the other. The lexicographical order of strings follows the single-character ASCII order.

Here are some examples of comparisons between sequences of the same type:

(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < ( 1 ,  2 ,  - 1 ) 
( 1 ,  2 ,  3 )              ==  ( 1.0 ,  2.0 ,  3.0 ) 
( 1 ,  2 ,  ( 'aa' ,  'ab' ))    <  ( 1 ,  2 ,  ( 'abc' ,  'a' ),  4 )

Note that if through <or >comparing object as long as the appropriate comparison method is legal. For example, mixed numeric types are compared by their values, so 0 is equal to 0.0. Otherwise the interpreter will trigger a TypeError exception instead of providing a random result.

Related Articles: 

Python Interview Questions

Python Programming Interview Questions

Leave a Comment