Lists in Python

Python Lists: Learn Python Lists in Detail with Real Examples
Written by Paayi Tech |19-Apr-2019 | 0 Comments | 150 Views

Python offers a range of data structure and list is one of the most important data structures in python. We will use a lot of list in our programming. It is flexible easy to use and fast to execute. Moreover, we can make iteration even faster by some modifications. Even we don’t have to specify the number of items that we have to insert, it is flexible and allow as many data as user wants to insert.

Python list is a built-in data structure in python. List is a collection of elements regardless of data type; python list can store both string and integer at the same time. We don’t have to specify the data type before initializing the list as in case of C, C++ or Java, etc.

 

How to initialize python list:

To initialize the python list, we have to set a variable with empty brackets or to set all the elements within a bracket separated by the coma. Moreover, we can give a different type of datatype like integer, float, and string and even other data structures within a list.

 

Example:

List1= []
 
List2 = [1, 2, 3, 4]
 
List3 = [1, 1.1, "Henery the Lion Heart"]
 
List4 = [ {"key":"value"}, (1, 2, 3), [1, 1.1, "Henery the Lion Heart"]]
 
In List4 first element is a dictionary, the second is a tuple, and the third one is a list.

 

Just like n-dimensional arrays, we can create nested lists in python as well. The elements can be added on a run time.

 

Nested List Example:

nested list = [[1,2,3,4], ['jacket','coat','shirt'], ['car', 'truck', 'bike']]

The above list is 3-dimensional list.

 

List Indexing:

One way of accessing the elements within a list is by list indexing. The index of the list starts with 0. The elements of the list can be accessed by the number of their index. The index is given within the square bracket, and it must be an integer. Following the example below of accessing the element by list indexing.

 

Example:

languages = ['java', 'python', 'c++', 'scala']
 
print(languages[0])

Output = java

 

print (languages [1])

Output = python

 

print (languages [2])

Output = c++

 

print (languages [3])

Output = scala

 

print (languages [4])

Error: list index out of range

 

Negative Indexing:

If we don’t know about the total number of elements within a list and want to access the last few elements of the list then we can do so by negative indexing. The method will be the same instead of using positive index we will use negative index:

Example:

languages = ['java', 'python', 'c++', 'scala']
print (languages [-1])

Output = scala

 

print (languages [-2])

Output = c++

 

print (languages [-3])

Output = python

 

print (languages [-4])

Output = java

 

 

List Slicing:

List slicing is a technique to extract a part of the list. The slicing returns an object of the list. This method allows for accessing a particular range of elements within a list. Syntax of doing slicing is “List [ initial:ending ]”. The procedure starts from the initial index and end at ending index but not include the element of ending index. Following is the example of list slicing:

Example:

languages = ['java', 'python', 'c++', 'scala','javascript']
print (languages [0:2])

Output = ['java', 'python']

 

print (languages [:-2])

Output = ['java', 'python', 'c++']

 

print (languages [:])

Output = ['java', 'python', 'c++', 'scala','javascript']

 

print (languages [3:5])

Output = ['scala', 'javascript']

 

Built-in Function Associated with List:

Python provides many built-in functions to handle the lists. These functions are not just handy but also very fast as compared to user-defined functions. Following are the functions.

  • max (): max returns the maximum value from the list. 
  • Len (): It returns the length of the list. It is to be noted the Len () function’s index starts from 1 whereas the list index starts from 0
  • sort (): Sort function returns the sorted list
  • min (): min function returns the minimum value from the list.

Example:

List = [100,65,32,75,33,12,9]
print (len (List)) In

Output = 7

 

print (max (List))

Output = 100

 

print (min (List))

Output = 9

 

print (sorted (List))

Output = [9, 12, 32, 33, 65, 75, 100]

 

print (sorted (List, reverse=True))

Output = [100, 75, 65, 33, 32, 12, 9]

 

Animal = ['cow','ant','zebra','goat']

Output = ['ant', 'cow', 'goat', 'zebra']

 

 

Mathematical Operators with List:

The mathematical operators like addition and multiplication can be used to manipulate the list elements. This can clearly understand by the following example:

List1 = [10,100,1000]
List2 = [20,200,2000]
 
List3 = List1+List2
 
List4 = [List1*3, List2*3]

 

print (List3)

Output = [10, 100, 1000, 20, 200, 2000]

 

print (List4)

Output = [[10, 100, 1000, 10, 100, 1000, 10, 100, 1000], [20, 200, 2000, 20, 200, 2000, 20, 200, 2000]]

 

 

Insert, Remove, Pop, Del, Append Operation:

Insert, remove, pop, del, append, clear operations are used to manage the elements within a list. Each operation has unique nature and functionality.

 

Insert:

Insert allow a user to insert a new value at the desired index. This function took two parameters the index at which new value is to be placed and the value itself e.g. “list (index, value)”.

 

Remove:

Remove allow the user to remove the element from the list by the value instead of index. It took one argument which is the value.

 

Pop:

The pop function will pop the element and returns. If no argument is given to pop function so by default it will return the value of the last index. If the index value is given then it will return that index value.

 

Del:

del () function will delete the list.

 

Append:

Append function add the value at the end of the list.

 

Clear:

Clear function will remove all the elements within a list and return an empty list.

 

Example:

List = [1,2,3,4]
List.append(999)

Output = [1, 2, 3, 4, 999]

 

List.insert(1,'inserted value')

Output = [1, 'inserted value',2, 3, 4, 999]

 

List.pop ()

Output = 999

 

List.pop (1)

Output = inserted value

 

List.clear()

Output = []

 

del (List)

Delete List

 

List Comprehension:

List comprehension is used to make code clean. It will make the list operation small as compared to normal ways of looping the list. Moreover by using lambda functions, map and reduce we can accelerate the iteration over a list.

Consider the following codes. Both perform the same operation, but the number of codes is so much less in list comprehensive code.

Code 1:
List_a = []
for i in range (10):
    List_a.append(10*i)
print (List_a)
 
Code 2:
print ([10*i for i in range (10)])

 

Lambda Expression and Map with a List:

Lambda expression is also known as the anonymous function are used with a list to perform the user-defined function. The normal approach is lengthy and time-consuming, but with the lambda expression, it is easy, clean and fast as generators are performed. Generators are the functions that return the object which is called the iterators over which we can iterate. The cost of iterators is much less than the normal for loop execution. The advantage of lambda can be seen when it is used by map functionality. Lambda returns the generators and map iterate over those values.

 

Normal Code
animal = ['cow','goat','zebra','owl','elephant']
ANIMAL = []
def make_capital (name, a_list):
    name = name.upper()
    a_list.append(name)
 
for e in animal:
    make_capital (e, ANIMAL)
print (ANIMAL)

Output = ['COW', 'GOAT', 'ZEBRA', 'OWL', 'ELEPHANT']

 

List Comprehension
animal = ['cow','goat','zebra','owl','elephant']
print (list (map (lambda x: x.upper(), animal)))

Output = ['COW', 'GOAT', 'ZEBRA', 'OWL', 'ELEPHANT']

Both perform the same functionality.

 

Conditional List Comprehension:

We can make condition like if and else in the list to make it comprehensive. The conventional way of doing this is to make a for loop and then append in another list which makes 3 to 4 lines of code easily. But in the list comprehension, we can do in just one line. Like in the table of 5 lists. I will do this in just one line to make our code cleaner and easier to manage.

 Code
 
print ([x for x in range (1,51) if x%5==0])

The above code will print all the number that are completely divisible by 5 in just one line.

 

Nested if conditions:

The above example involves only one if the condition. However, we can also make nested if condition for complex problems required. For example, if we have to check multiple conditions, then we can do as follows.

 Code
 
print ([x for x in range (1,101) if x%10==0 if x%30==0])

The above code will first check if the number is completely divisible by 10 and then check if the number is completely divisible by 30. and it will give the output of [30,60,90].

 

If Else Condition:

We can also use if and else both in a list comprehension. See code below.

Code
 
print (["Even" if x%2==0 else "Odd" for x in range (10)])

 

In the above code, we have written a condition on a range starting from 0 to 10 that if the value is even returned even else return odd. The list that returns will be as follows:

Output
 
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']

 

As you can see from the above output values been replaced by the even and odd. In a conventional way of coding, it will require almost 4 to 5 lines to execute such a task in python.



Login/Sign Up

Comments




Related Posts



© Copyright 2019, All Rights Reserved. paayi.com

This site uses cookies. By continuing to use this site or clicking "I Agree", you agree to the use of cookies. Read our cookies policy and privacy statement for more information.