Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Friday, 28 October 2016

Python List Comprehension, Concatenation, Repetition, Index and Slice

Hello readers! In some of our recent articles we have learned about Python Strings - How they are created, how they are concatenated and repeated, how they are indexed and sliced, and a bunch of methods associated with them. In the similar way, we will be learning about another Python object here- Lists. In this article, we are going to know about Python lists properties and basic operations, including List creation, concatenation, repetition, etc., those can be performed on them. But, first of all, we see what lists are.



A Python List is a sequence of Python objects (strings, integers, lists, dictionaries, tuples, etc), each of them being separated by comma, enclosed in square ([ ]) brackets. Everything in Python being an object, makes a Python list an object, and every list is an instance of Python built-in list class. In brief, its a Python object that is created with the help of a few or more Python objects (empty lists do not contain any element, though). Moreover, it being a sequence (like Python strings), each item contained within a list is assigned with an index, using which a list can easily be sliced (like Python strings, again). Let's dig deeper into the lists!

Creating Lists

To begin with, lets create an empty list. As mentioned earlier, a list is a sequence of Python objects enclosed between two square brackets. When we don't mention anything inside the brackets, it creates an empty list for us. Another method is to use list() function, it receives a string parameter and returns a list type. When we do not specify any parameters to list() function, it returns an empty list.

>>> myList = []
>>> myList
[]

>>> myList2 = list()
>>> myList2
[]

Simple! Now, we create a non-empty list by putting Python objects between the square brackets.

# A list of Integers
>>> myList = [1, 2, 3, 4, 5]
>>> myList
[1, 2, 3, 4, 5]

# A list of Strings
>>> myList = ['Real Madrid', 'Barcelona', 'Manchester United', 'Liverpool']
>>> myList
['Real Madrid', 'Barcelona', 'Manchester United', 'Liverpool']

# A list of Lists
>>> myList = [['a', 'b', 'c'], ['d', 'e', 'f'], ['x', 'y', 'z']]
>>> myList
[['a', 'b', 'c'], ['d', 'e', 'f'], ['x', 'y', 'z']]

# A list of Dictionaries
>>> myList = [{'String' : 'Apple', 'Integer' : 101}, {'Website' : 'CodeNinja', 'Topic' : 'Python Lists'}]
>>> myList
[{'Integer': 101, 'String': 'Apple'}, {'Website': 'CodeNinja', 'Topic': 'Python Lists'}]

# A list of mixed objects
>>> myList = ['I<3Python', 7, ['Asia', 'America', 'Europe'], {'Movie': 'The Revenant', 'Year' : 2015}]
>>> myList
['I<3Python', 7, ['Asia', 'America', 'Europe'], {'Movie': 'The Revenant', 'Year': 2015}]

Awesome! We now check what type this list variable myList belongs to, by using built-in type() function.

>>> type(myList)
<type 'list'>

Thus, myList is of type list or it is an instance of list class.

Another way to create a list is using for-in statement. As we are new to for statement, I will demonstrate list creation using strings. The for statement uses a variable to iterate through each item of the string. Using this variable, we can put each item of the string inside square brackets, to create a list. Sounds difficult? No worries, just have a look at the example below, we will break the statement for easier understanding.

>>> myString = "ABCDEFXYZ"
>>> [var for var in myString]
['A', 'B', 'C', 'D', 'E', 'F', 'X', 'Y', 'Z']

In above example, we start from right end and take out a portion of the command - for var in myString. In this statement, for uses a variable var to iterate over the items of the string myString. So, in the first iteration, var is assigned with the value of first item of the string i.e. A, while in the second iteration, var gets the value of second item of the string i.e. B and so on. But, we haven't made use of this variable var yet. So, in the entire command, we loop over each item of the string and using var before for, we actually use each value assigned to it, and enclosing it in square brackets returns us a list. In short, this is equivalent to [ sequence of values assigned to var ], an object of list type.

I cannot stop myself from mentioning about a Python built-in function range() here. The syntax for using range() function is - range([START], STOP, [STEP]), where START and STEP are optional parameters. This function returns a list of numbers starting from START ('0' if not provided) up to but not including the number END, including every STEPth number. Lets see some examples on range() function.

# Starting from '0' ending but not including '7'
>>> range(7)
[0, 1, 2, 3, 4, 5, 6]

# Starting from '2' ending but not including '9'
>>> range(2, 9)
[2, 3, 4, 5, 6, 7, 8]

# Starting from '1' ending but not
# including '11', including every '3'rd element 
>>> range(1, 11, 3)
[1, 4, 7, 10]

# What type of object does it return?
>>> type(range(1, 11, 3))
<type 'list'>

List Concatenation and Repetition

Just like strings, Python lists can also be concatenated, using + sign. Lets check this over terminal.

>>> myList1 = ['Hello', 'World']
>>> myList2 = [1, 4, 9, 16, 25]
>>> myList3 = ['Ten', 20, 'Thirty', 40]

>>> myList1 + myList2 + myList3
['Hello', 'World', 1, 4, 9, 16, 25, 'Ten', 20, 'Thirty', 40]

>>> type(myList1 + myList2 + myList3)
<type 'list'>

Easy! In above example, we concatenated three lists using + operator, which returns a list object. Now, we will check what would be the result if we concatenate a list object with a str object.

>>> myList = ['Code', 'Ninja', 'Dot', 'In']
>>> myStr = "Code Ninja Dot In"
>>> myList + myStr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

Aaanndd.. The result is an Exception which says - TypeError: can only concatenate list (not "str") to list. That means, we cannot concatenate a list object with a str object. In order to concatenate str object with list object, we must convert str object to listtype, using Python built-in list() function as shown below.

# This is the 'string' type object
>>> myStr = "Code Ninja"
>>> type(myStr)
<type 'str'>

# It becomes a list when passed to 'list()' function
>>> list(myStr)
['C', 'o', 'd', 'e', ' ', 'N', 'i', 'n', 'j', 'a']
>>> type(list(myStr))
<type 'list'>

# This is the 'list' type object
>>> myList = [1, 2, 3]
>>> type(myList)
<type 'list'>

# We concatenate both 'list' type objects
>>> myList + list(myStr)
[1, 2, 3, 'C', 'o', 'd', 'e', ' ', 'N', 'i', 'n', 'j', 'a']

In the same manner, we can use * operator to create a repeated sequence of list elements as below:

>>> myList = ['One', 2, 'Three', 4]
>>> myList * 4
['One', 2, 'Three', 4, 'One', 2, 'Three', 4, 'One', 2, 'Three', 4, 'One', 2, 'Three', 4]

List Indexing and Slicing

As we have already seen in the case of Python Strings, every Python List is also a sequence of elements and are associated with positional parameters, i.e. 'Index'. With these indices, we can determine the length of a list (number of elements in a list), we can access elements in a list, we can insert/remove list items and even slice the lists. The indexing in the list, like strings, starts from zero, counting from left to right. Thus, first list item is listName[0], second list item will be listName[1] and so on. Python lists also support negative indexing, for accessing list items from right to left. Thus, for long lists, we can access last list element using listName[-1], second last list element with listName[-1], without actually doing any mathematics.

List slicing is the process of extracting a portion of list from an original list. We just have to mention the START index, STOP index and an optional parameter STEP (with default value as '1'). So, the syntax for List slicing becomes - listName[START : END [: STEP]]. Thus, myList[2:8] will return a list object, including elements from the list myList, starting from element at index '2' (third element) up to but not including element at index '8'. If we do not mention the value for END index, it will default to the index of the last item in the list, while in case we do not mention the value for START index, it will default to the index of the first element i.e. '0'. Apparently, not mentioning START and END indices will return the original list.

As mentioned earlier, we have an optional parameter - STEP, which gets added to the index whenever an item is extracted from the list. So, listName[START:END:STEP] extracts every STEPth element from the list listName starting with element at index START up to but not including element at index END.
Below examples will provide a clearer view on what we have studied in this section.

>>> myList = ['I<3Python', 7, ['Asia', 'America', 'Europe'], {'Movie': 'The Revenant', 'Year': 2015}]

# Accessing the first element of the list
>>> myList[0]
'I<3Python'

# Accessing the third element of the list
>>> myList[2]
['Asia', 'America', 'Europe']

# Index of the Index - Accessing the second element of third element of the list
>>> myList[2][1]
'America'

>>> myList[3]['Year']
2015

# We create a new list to demonstrate Negative Indexing and List Slicing
>>> myList = range(13)
>>> myList
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

# Determining length of the list using 'len()' function
>>> len(myList)
13

# Accessing the last element using index '-1'
>>> myList[-1]
12

# Accessing the fourth last element using index '-4'
>>> myList[-4]
9

# List slice starting from element at index '2' 
# up to but excluding element at index '8' 
>>> myList[2:8]
[2, 3, 4, 5, 6, 7]

# List slice starting from element at index '4' up to last element
>>> myList[4:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]

# List slice starting from beginning,
# up to but not including element at index '9'
>>> myList[:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]

# The complete slice
>>> myList[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

# Slice of the list including every 3rd element
# starting from element at index '2'
>>> myList[2::3]
[2, 5, 8, 11]

# Slice of the list including every other element
# starting from element at index '1' 
# up to but excluding the element at index '10'
>>> myList[1:10:2]
[1, 3, 5, 7, 9]

# List reversal using STEP = -1
>>> myList[::-1]
[12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

# Another example with negative STEP
>>> myList[10:0:-2]
[10, 8, 6, 4, 2]

Lists are 'Mutable'!

Python objects are said to be 'Mutable', if their value is changeable i.e. they can be modified, otherwise they are called as 'Immutable'. To determine whether Lists are mutable or not (I've already determined it in the section title :)), we try to change the value of the list element as shown below:

>>> myList = ['I<3Python', 7, ['Asia', 'America', 'Europe'], {'Movie': 'The Revenant', 'Year': 2015}]
>>> myList
['I<3Python', 7, ['Asia', 'America', 'Europe'], {'Movie': 'The Revenant', 'Year': 2015}]

>>> myList[2] = 'ReplacedValue'
>>> myList
['I<3Python', 7, 'ReplacedValue', {'Movie': 'The Revenant', 'Year': 2015}]

Success, we have modified a List! With this, we can conclude that List objects are Mutable!.

So, in this article, we have learned what Python lists are, how they can be created and basic operations, like concatenation, repetition, indexing & slicing, associated with them. In the next article on Python lists, we would be learning about the methods associated with them. If you have anything to say about this article, please share your views in the comment section below. Thank you!

This article is originally published at www.codeninja.in - Python Lists - Creation, Concatenation, Repetition, Indexing and Slicing

0 comments:

Post a Comment