Data Structures in Python-Introduction

In the previous sections of this Mastering Python for Blockchain series, we read about the Data Structures in Python-Tuples. This article will focus on the Data Structures in Python-Lists. There are other Data Structures in Python like sets, dictionaries, which we will learn in the upcoming parts of this Mastering Python for Blockchain Series. If you have not read the previous parts of this Mastering Python for Blockchain Series, please do read them. It will help you build your Python foundation from the beginning. Start from here.

Few quick words: I will suggest you to download the latest version of Python which will help you to practice coding and compiling programs. In case you do not have Python installed in your system you can use this link to online run your Python codes.

I also suggest you to visit the article here to learn the basic concepts of Blockchain.

Data Structures in Python-Lists

In the previous sections, we learnt about strings. Strings are a sequence of characters. Right?

In Python, besides strings, we do have other sequences-Tuples and Lists. Tuples we learnt here. These are Data Structures in Python which are basically sequence of zero or more elements. These elements can be any Python objects.

Tuples are immutable whereas Lists are mutable. This means, once you assign elements in a Tuple, it is baked into the cake. The elements cannot be changed. Whereas, the elements in a List can be changed.

Lists

  • Lists are used for keeping track of things by their order, especially when the order and contents might change.
  • Unlike strings and tuples, lists are mutable. This means, you can change a list in place, add new elements, replace or delete existing elements. Even the same value can occur more than once in a list.

Syntax

Lists are made up of zero or more elements, separated by commas and surrounded by square brackets.
list=[‘element1’, ‘element2’, ‘element3’,…]

list( ) function

The list( ) function can be used to create an empty list or convert any iterable data types like strings, tuples, sets and dictionaries to lists.

split( ) function

split( ) function is used to chop off a string into a list by some separator.

What if you have more than one separator string in a row in your original string? Well, you get
an empty string as a list item:

What if we had used // as the separator.

[offset]

  • As with strings, we can extract a single value or element of a list, by specifying its offset.
  • As with strings, left to right, the count starts from 0 and increases by 1. From right to left the count starts from -1 and decreases by -1.

Note: An offset has to be a valid one, a position to which a value is assigned in the list. Otherwise, Python will raise an exception.

Get a sub-list by slicing a list (using colon ‘:’)

  • Slicing is frequently used in Python. We can get a sub-sequence of a list using slice.
  • Syntaxlist_name[start:end:offset_jump]
  • Here start is from where the list is to be sliced. It has the default value of 0
  • end is till when the list is to be sliced. In fact list is sliced till end-1. It has the default value of the last element of the list from left to right
  • offset_jump is the number of elements to be jumped from the start. It has the default value of 1

See some of the examples of list slicing below.

Now let us see, how to reverse a list.

Some negative indexing

Note: As in the case of strings, slicing of lists cannot return an exception for an invalid offset/index. It will either snap to the closest valid index or return nothing. See below.

append( ) function: to insert an element at the end of the list

If you want to insert an element at the end of a list then use the append( ) function.

insert( ) function: to add an element before any offset in a list

An offset beyond the end of the list inserts at the end, like append(), so you don’t need to worry about Python throwing an exception:

Operator + or extend( ) function to combine lists

We can use the += or extend() function to merge a list into an existing list.

Let us first see how to use += operator.

Now, let us see how to use extend( ) function.

Note: If we used the append() function, it would have added list weekend as a single list element. See below.

This again proves that a list can contain elements of different types. In this case four strings and a list of two strings.

Operator *

Operator can be used to duplicate lists.

Modifying the items of a list

CHANGE AN ITEM USING THE [OFFSET]
CHANGE ITEMS WITH SLICE

We have seen how to get a sub-list with a slice. Now we will see how to assign values to a sub-list.

The right hand things that you are assigning to the list does not need to have the same number of elements as the slice on the left.

Another one,

In fact the right hand does not need to be even a list. Any Python iterable(strings, tuples, dictionaries) will do. See below.

DELETE AN ELEMENT AT AN OFFSET BY DEL

Let us assume we need to remove Poornaviram from the list (as he is not one of the brothers among Ram, Shyam and Ghanshyam.

Note: del is a Python statement, not a function. You do not write list[-1].del( ).

del can also be used to delete elements in sub-list.

DELETE AN ITEM BY REMOVE( )

If we are not sure about the offset of an item or where an item is in a list, we can delete it by using the remove( ) function.

Note: If the list contained duplicate elements with the same values, then remove( ) deletes only the first one it finds.

POP( ) FUNCTION-GET AN ITEM OF A LIST AND DELETE IT AT THE SAME TIME
  • The pop( ) function is used to get an element of a list and at the same time delete it from the list.
  • It uses the offset as its argument.
  • pop(offset) will get the element at the ‘offset’ in the list and delete it from the list at the same time.
  • The pop ( ) function uses -1 as its default argument. So the pop( ) removes the element at the tail end of the list by default.
  • Syntax: list.pop( )
CLEAR( ) FUNCTION TO CLEAR ALL THE ITEMS IN A LIST
  • Python 3.3 introduced a method to clear all the elements of a list, by using the clear( ) function.
  • It deletes all the elements of a list and makes it a null list.
  • Syntax: list.clear( )
INDEX( ) TO FIND THE OFFSET VALUE OF AN ELEMENT IN A LIST
  • The index( ) function is used to find out the offset value of an element of a list.
  • Syntax: list.index(Element for which the offset value has to be found)
  • If an element is found more than once in a list, then only the offset of the first element from the left is returned
CHECK FOR THE OCCURRENCE OF AN ELEMENT IN A LIST BY USING IN

Syntax: ‘Element’ in list

Output:

COUNT( ) FUNCTION TO FIND OUT THE NUMBER OF TIMES AN ELEMENT APPEARS IN A LIST

Syntax: list.count(element for which the number of occurrences in the list is to be found)

Output:

JOIN( ) FUNCTION TO CONEVRT A LIST TO A STRING
  • You can convert a list into a string by using the join( ) function.
  • join( ) function will take the list as its argument.

Output:

SORT( ) AND SORTED( ) FUNCTIONS: TO SORT A LIST
  • We can sort the items/elements in a list in Python.
  • For sorting, python gives us two functions: sort( ) and sorted( )
  • The list method sort( ), sorts the items of the list. For numbers in lists, it arranges them in the ascending order. Whereas for strings in the list, the sort( ) function arranges the list in the alphabetical order.
  • The sort( ) function changes the original list to a new list with the sorted items.

Output:

  • The sorted( ) function returns a new list by sorting the original list.

Output:

  • If the elements of your list are all of the same type (such as strings in names list used above ), sort() will work correctly. You can sometimes even mix types—for example, integers and floats—because they are automatically converted to one another by Python in expressions

Output:

  • The default sorting order is ascending, but we can sort a list in the descending order by using the argument reverse=True for sort( ) function.

Output:

LEN( ): TO GET THE LENGTH OF A LIST
  • len( ) function returns the number of items in a list or the length of a list.
  • No matter, if items are repeated, the len( ) function counts the repeated items also.
ASSIGN WITH =

Let’s say we assign a list to a variable.

a= [1,2,3]

We assign this list to another variable ‘b’

b=a

We again assign this list to a third variable ‘c’

c=a

What do you think will happen to lists assigned to ‘b’ and ‘c’ when we change the elements of list ‘a’.

Output:

As we can see, when we changed one of the elements of ‘a’, the elements of lists ‘b’ and ‘c’ also changed.

In fact, when we assign a list to more than one variable, changing the list at one place changes at other places also.

This abides by the object and variable analogy we have explained earlier in our Mastering Python for Blockchain series. The list is stored in computer memory called ‘object’. All the variables represent the same object in the computer’s memory.

COPY( ), LIST( ), SLICE: TO COPY A LIST TO A FRESH LIST
  • We can copy a list to a fresh new list by using the copy( ) method, list( ) conversion function and with a list slice [:]
  • Unlike earlier (using the =), in this case all the lists are at different objects in the computer memory. Hence changing the elements in one list will not change the elements in the other list.

Output:

Let us now see how to apply the list( ) conversion function.

Output:

And finally the slice [:]

Output:

DEEPCOPY( ): COPY A LIST TO A NEW LIST COMPLETELY
  • copy( ), list( ) and slice, work well till the elements in a list are immutable.
  • For example, in the list a = [1,2,3], the elements 1,2 and 3 are immutable. But when the elements in the list are mutable (like lists, dictionaries), the copy( ), list( ) and [: ] do not work completely. Changing the mutable element in the original or the copied list changes the elements in the other list.

Output:

  • In these case where we do not want a change in the original or the copied list to impact the other one, we use the deepcopy( ) function.

Output:

COMPARE LISTS WITH COMPARISON OPERATORS <,==,>

Output

1 Comment

Leave a Reply