In the previous sections of this Mastering Python for Blockchain series, we read about different Data types in Python-Booleans, Integers, Floats and Strings. These Data Types in Python are like atoms. When we combine these Data Types, we get Data Structures in Python. This article focusses on the Data Structures in Python-Tuples and 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-Tuples and Lists: Definition

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

Tuples

This is the first Data Structures in Python, we are getting apprised of. How do you pronounce Tuple? Guido van Rossum, the creator of Python, said via Twitter:
I pronounce tuple too-pull on Mon/Wed/Fri and tub-pull on Tue/Thu/Sat. On Sunday I don’t
talk about them. 🙂

Syntax:

Tuples are created with either a comma, parenthesis or a comma and a parenthesis. It is a bit inconsistent. See below:

Empty Tuple:

empty_tuple=( )

Tuple with a single element

single_element_tuple=’Tuple’, ##see we used a comma
or
single_element_tuple=(‘Tuple’,) ##we used comma as well as parenthesis.
If we only used parenthesis and no comma in a single element Tuple, it would create a string.

Tuple with multiple elements

multiple_element_tuple=’Element1′, ‘Element2’, ‘Element3’
##follow all but the last one with commas

or,

multiple_element_tuple=(‘Element1’, ‘Element2’, ‘Element3’)

Tuple Unpacking

Tuples can be used to assign values to multiple variables. See below.

Output:

In the second line, Python assigns the three variables, land_animal, water_animal and amphibian the elements of Tuple tuple. This assignment occurs in the order of sequence in which the elements appear. This means the first element ‘horse’ is assigned to the first variable land_animal, the second element fish is assigned to the second variable water_animal, and so on. This phenomena is called Tuple Unpacking.

Exchange values of variables

Tuples can be used to exchange the values of variables in a single line. See below.

Output:

tuple( ) function

The tuple( ) function is used to create a tuple out of any other data type in Python.

Outputs:

Operators +,* and comparison operators

Output:

Output:

Output:

Iterate with for and in

Output:

Another one,

Modify a Tuple

You cannot. Just like strings, Tuple also can’t be modified. It only seems that the tuple is modified. Tuples are immutable.

In the above example, it only appears that the tuple t1 has been modified. In fact, Python created a new tuple t1 from the old tuple t1 by t1+=t1.

You can in fact check the different ids of the two tuples.

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.
  • Syntax: list_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.

Leave a Reply