LIST IN PYTHON

 

Hey Shouters!! Today we learn about all the important functions on lists in python.

In this tutorial, we will learn about all the important things about the Lists. The main parts that we will learn about are:

  1. Definition of List
  2. String and list similarities
  3. Declaration and Initialization
  4. Slice and Index Operations Over List
  5. Going through a List
  6. Update a List
  7. Nested List
  8. Some Examples Of List
  9. Methods
  10. Add Elements to a List
  11. Deleting an Item From a List
  12. All important functions

Definition of Lists in Python-

The list is an abstract datatype. In Python, A-class ‘list’ is present with multiple methods. The list is a build-in mutable sequence.

The list does not follow FIFO or LIFO techniques. Insertion and deletion can take in any position.

Similarities between STRINGS AND LISTS-

Strings are basically a sequence of characters. Similarly, Lists are basically a sequence of values. These values are Mutable values. That means We can update those values in our program. But Strings are immutable values that cannot be updated. But concatenation, slicing operations can be done with strings. Similarly, Slicing operations and concatenation operations are done with the list also.

Similar to array concept, List values are extracted using Third bracket(‘[]’).

In general case, we somehow say that, This a list of purchasing items.

Similarly, In python, a List is used for storing values that can be any type. The list can contain a list also. Type need not be uniform.

Some examples of lists are given below:

Awards=[]

How To Declare and Initialize a List?

To declare a string, we basically use a list_name, an assignment operator, and a third bracket where values may be present.
For example,
Laptop_Company_names = [‘DELL’,’HP’,’SAMSUNG’,’APPLE’,’ASUS’]

Here, ‘Laptop_Company_names’ is a list name with an assignment operator (=) followed by list of values i.e. [‘DELL’,’HP’,’SAMSUNG’,’APPLE’,’ASUS’]

Some Advance and time saving method is given below to initialize a list :

This is a list of 100 elements starting from 0 to 99.

We can use if statement inside it also. Let’s go for it.

This is a list of 5 elements i.e. [0,2,4,6,8], starting from 0 to 9 and check that ‘i’ is even or not. If even then it is added to the list Otherwise Not.

Declare an empty list :
If no argument is given, the constructor creates a new empty list. i.e.

Remember that, For list third bracket(‘[‘,’]’) is compulsory.

USING LIST CLASS, OBJECT INITIALIZATION:

To convert any other datatype to List (abstract data type) we can use ‘List’
EXAMPLE:
numbers= list(range(10))

output:
[0,1,2,3,4,5,6,7,8,9]

Note that, list takes only one argument as input and returns a list.

It is also useful when we use conversions between different abstract data types.

Note: Python changes Single Cot(”), Double Cot(“”), Triple Cot(“”” “””) into Single Cot(”) for list of string type elements. Remember that, Integer and Floting-point type elements need not use any Cot. They are use without any Cot.

SLICE AND INDEX OPERATIONS OVER LIST-

If indexing is used then List return a value. If Slicing operators are used then List returns another list(a subset of the original list).

For example,
Prime_num = [2,3,5,7,11,13,…]
Here, we declare a list of prime numbers.
Now,
Prime_num[0]==2
gives result ‘True’ because That is a value(integer type).

But,
Prime_num[0:2] == [2,3]
gives result ‘True’ because That is a list( subset of prime numbers. )

Note, List and Integer values are not same.

SLICING OPERATION –

The syntax of slice is:
new_list = list_name[ start : end: step]
Here, ‘new_list’ is used as a New List name as slice operation returns a list. ‘list_name’ is used as a already declared list. ‘Start’ means Starting position, ‘end’ means Ending position, and ‘step ‘ means in each pass no of steps taken to move in the index.
Negative value also supported here.

Right to left
-5 -4 -3 -2 -1
Letters= [‘a’,’b’,’c’,’d’,’e’]
0 1 2 3 4
left to right

NOTE: As we move first index to last, we start from 0 to n-1 where n is the length from left to right side.
For Negative indexing, we start from -1 to -n where n is the length and Negative indexing used from right side to left side.

For example :

Here, we apply slicing operation on Letters.

Output:
[‘a’,’b’,’c’]

GOING THROUGH A LIST –

  • List have a grate advantage that is we can access each elements using an index value.

Here, We use a for loop to iterate through the list and access values.

For example,
Integer=[‘-Infinity’,’…’,-1,0,1,2,’…’,’+Infinity’]
for i in range(len(Integer)):
print(Integer[i],end=” “)
Output:
-Infinity … -1 0 1 2 … +Infinity

Some people use a while loop, Let’s see the same example using a while loop.
Integer=[‘-Infinity’,’…’,-1,0,1,2,’…’,’+Infinity’]
i=0
while(i < len(Integer)):
print(Integer[i],end=” “)
i=i+1
Output will be same.

To access each element from the list we use square bracket with index number( [i]).

UPDATE A LIST-

A list can be updated without affecting others.
List follows mutuable property that means list can be updatable.
Updating a list can be done through index of that item.

EXAMPLE:
Mode=[‘ON’,’OFF’]
#update ‘ON ‘ to 1 an ‘OFF’ to 0
Mode[0]=1
Mode[1]=0
print(Mode)
OUTPUT:
[1, 0]

NESTED LIST-

A List can contain another list, that is called list of lists or Nested list.

EXAMPLE:
list_Of_List=[ [01,02,03],
[11,12,13],
[21,22,23]]

Here, we take [01, 02, 03] as 0th index element for outerlist and so on.
With in inner list, value ’01’ is at 0th index element for innerlist and so on.

Inner List can contain elements as a simple list.

To traverse list_Of_List or Nested List, we consider loops.
EXAMPLE:
list_Of_List=[ [01,02,03],
[11,12,13],
[21,22,23]]

Consider the matrix :
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12] ]
The following list comprehension will transpose rows and columns:
CODE:
[[row[i] for row in matrix] for i in range(4)]
OUTPUT:
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

SOME EXAMPLES OF LIST-

EXAMPLE 1:
for i in [1,2,3]:
print(i,end=” “)

Output:
1 2 3

Here, We use list as an iterable entity. ‘i’ takes each element one by one and prints the result.

Note: Unlike escaping the last element, if we provide a list then all list elements are iterable.

EXAMPLE 2:
li=[1,2,3]
li=li+li
print(li)
Output:
[1,2,3,1,2,3]

Here, ‘+’ operater is used as Concatenation operation, Not index wise addition operation.
Here, Python interpreter used ‘add‘ magic function(discussed later.)

EXAMPLE 3:
lst = [‘Ball’,’Box’,’Bag’]
print(lst[-1])

output:
Bag
here, we peek the last element of the list(‘lst’) using negiative indices (discussed later).

EXAMPLE 4:
list_of_lists=[[]]
list=[]
print(list in list_of_lists)
print(list in list_of_lists[0])
Output:
True
False

EXAMPLE 5:
import keyword
print(keyword.kwlist)

Output:
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

EXAMPLE 6:
a,b=20,[30,40,50]
print(a)
print(b)
print(type(a))
print(type(b))
Output:
20
[30,40,50]

EXAMPLE 7:
myList = [10, 1, 8, 3, 5]
total = 0
for i in myList:
total += i
print(total)

Output:
27

METHODS-

  1. Magic methods –
  • Some methods are used for very special purposes for Python Interpreter.
  • These magic methods in Python are the methods having two prefix and suffix underscores in the method name.
  • Magic functions can be overloaded.
  • We can check hidden magic methods via, ‘dir(object)’ function. Overview of Magic Methods
    Binary Operators
    Operator Method
  • add(self,other)
  • mul(self, value, other)
    etc. There are many magic functions in Python. We will discuss in later sections.

ADD ELEMENTS TO A LIST –

There are 4 methods to add elements to a List in Python.
I. Append method
II. Extend method
III. Insert method
IV. List Concatenation

I. Append Method
Syntax:

Here, ‘list_name’ indicates the name of the list.
‘value’ indicates the object that appends to the end of the list.

EXAMPLE:
Flowers=[“Rose”,”Tulip”]
print(” Before: “, Flowers)
Flowers.append(“Lily”)
print(” After: “, Flowers)

Output:
Before: [‘Rose’, ‘Tulip’]
After: [‘Rose’, ‘Tulip’,’Lily’]

II. EXTEND METHOD
Syntax:
list_name.extend(iterable)

Here, ‘list_name’ indicates the name of the list.
‘iterable’ indicates the object that appends to the end of the list individually element by element.
It is useful to append elements from an iterable to the end of the list.

EXAMPLE:
Flowers=[“Rose”,”Tulip”]
print(” Before: “, Flowers)
Flowers.extend(“Lily”)
print(” After: “, Flowers)
Flowers.extend([“Lily”,”Orchid”])
print(” After: “, Flowers)
Output:
Before: [‘Rose’, ‘Tulip’]
After: [‘Rose’, ‘Tulip’, ‘L’, ‘i’, ‘l’, ‘y’]
After: [‘Rose’, ‘Tulip’, ‘L’, ‘i’, ‘l’, ‘y’, ‘Lily’,’Orchid’]

This function append iterable elements to the list.

Let’s use tuple as an argument of extend method.
EXAMPLE:
number=[]
print(number)
number.extend((3,4))
print(number)

Output:
[1, 3]
To append a tuple to list, we can use extend function.

Let’s use set as an argument of extend method.
EXAMPLE:
number=[]
print(number)
number.extend({3,4})
print(number)

Output:
[1, 3]

To append set to list, we can use the extend method.

III. INSERT METHOD
Insert method is used to insert an item to the specified index position.
Syntax:
list_name.insert(i, value)

Here, ‘i’ is the index position where ‘value’ is inserted. All the elements after the ‘value’ are shifted to the right.
If ‘i’ is 0 then inserted at the beginning of the list.
If ‘i’ is 2 then the element inserted after the 2nd element. Its position will be 3rd.
If ‘i’ value cross the list range then it is inserted at the end of the list.

Note: The insert() method doesnot return anything, returns None. It only updates the current list.

EXAMPLE:
fibo=[0,1,1,2,3,5]
fibo.insert(6,8)
fibo.insert(8,13)
print(fibo)
output:
[0,1,1,2,3,5,8,13]

EXAMPLE 2:
temp=[(1,2),[5,6,7]]
set1={3,4}
temp.insert(1,set1)
print(temp)
OUTPUT:
[(1,2),{3,4},[5,6,7]]

IV. List Concatenation
The ‘+’ operator are used to concatenate the lists.
List concatenation are done at the end of the first list.

It is very easy to add to list, unlike variable, list values are not added but after the first list, second list values are inserted.

After performing concatenation operation it returns a new list.

EXAMPLE:
D1=[“MONDAY”,”TUESDAY”,”WEDNESDAY”]
D2=[“THURSDAY”,”FRIDAY”,”SATURDAY”,”SUNDAY”]
print(D1+D2)
print(len(D1+D2))

print(D1-D2) NOT POSSIBLE

OUTPUT:
[“MONDAY”,”TUESDAY”,”WEDNESDAY”,”THURSDAY”,”FRIDAY”,”SATURDAY”,”SUNDAY”]
7

LENGTH OF A LIST :

Similar to String, ‘len()’ function is used to get the length of the string.

Remember that, length function starts counting from 1 not from 0.
For example,

list1=[‘A for Apple’]
len(list1)
1
Here, Length function gives the length 1 not 0.
so, For 0th index position length is 1 for 1st postion length is 2 and so on.

EqualsTo (=) Operator:

EqualsTo operator are used to assign the righthand side object values to lefthand side object.
Let’s check that in List equals to operator are works in which manner.

Example:
list1=[1,2,3]
list2=list1
print(list2)
c=list1.pop()
list1=[2.3,4.4,5.1]
print(list2)

Output:
[1,2,3]
[1,2]

Here, Notice that after assign the values of list1 into list2, list1 values are changes but list2 values are no affected afterall. Because it is similar to a variable assignment.

Drawback is that after attempting pop operation using the list1, affects the list2 also. We cannot create proper copy of it.(Copy() method discussed later)

DELETING AN ITEM FROM A LIST –

To delete an item is now not so difficult. Here, We need some understanding in the positions and values.

I. DEL METHOD
II. REMOVE METHOD
III. CLEAR METHOD
IV: POP METHOD

I. DEL METHOD:

To remove an item of specified index we use ‘del’ method.

Syntax:
del list_name[‘index’]

EXAMPLE:
Accounts=[‘Asset’, ‘Liability’,’Expenses’,’Business’,’Shares’]
# to delete the last element, we use del method
del Accounts[4]

OUTPUT:
[‘Asset’, ‘Liability’, ‘Expenses’, ‘Business’]

II. REMOVE METHOD:
To remove a specific element then we use ‘remove(value) ‘ method, where value is ‘the deleted item’.

  • If the deleted item is not present in the list, it generates Runtime error i.e. ValueError, value not in list.
  • If the deleted item is present more than once in a list, then first item is deleted.
  • It does not return any value( returns None).
  • Syntax:
    list_name.remove(obj)

EXAMPLE:
Accounts=[‘Asset’, ‘Liability’,’Expenses’,’Business’]
# to remove ‘Business’ we use remove method
Accounts.remove(“Business”)
print(Accounts)

OUTPUT:
[‘Asset’, ‘Liability’,’Expenses’]

III. CLEAR METHOD:
To Remove all items from a list, we use clear() method.
syntax:
list_name.clear()

l=[1,2,3,4,5]
print(l)
l.clear()
print(l)

[1,2,3,4,5]
[]

NOTE: All elements from this list is removed but list is present and allocates some memory later we can append values in it.

To delete properly a list we use del method, for example,
l=[1,2,3]
print(l)
del (l)
print(l)
output:
[1,2,3]
NameError, name ‘l’ is not defined

IV: POP METHOD
=> It returns removed value.
=> It generates IndexError exception on runtime if any mismatch in the index position.

list.pop(pos)

pos is optional. A number specifying the posotion of the element you want to remove. Default value is -1 which returns the last item.

Example:
car=[‘HONDA’,’BMW’,’NISSAN’,’FORD’]
print(car)
car.pop()
print(car)
car.pop(1)
print(car)

Output:
[‘HONDA’,’BMW’,’NISSAN’,’FORD’]
[‘HONDA’,’BMW’,’NISSAN’]
[‘HONDA’,’NISSAN’]

REMEMBER: Using slicing operation, we can delete some element from the list.

INDEX METHOD :
=> It returns the first index of the value.
=> A valueError will raise, if the value is not present.

syntax :
list.index(value)

EXAMPLE:
demo=[‘mobile’, ‘laptop’, ‘book’]
print(demo.index(“mobile”))

output:
0

COUNT METHOD :
=> Return number of occurance of value
=> It takes a single argument
Syntax:
list.count(element)

EXAMPLE:
person=[‘single’, ‘married’,’single’, ‘married’]
count=person.count(‘single’)
print(count)
Output:
2

REVERSE METHOD :
=> Reverse() method is used to reverse the list.
=> It does not return any value
=> It updates the original list

Syntax:
list.reverse()

Example:
palindrome=[‘level’,’madam’]
palindrome.reverse()
print(palindrome)
output:
[‘madam’,’level’]

SORT METHOD:
=> Sorting means arranging the elements via its property or value or ASCII character set.

=> It takes no arguments

=> It returns none.

=> It is a QUick sort

SYNTAX:
list.sort(key= , reverse= )
where key is used for function calling
and reverse is used to indicate ascending order or descending order.

EXAMPLE:
def sorts(val):
return val[0]

li=[(1,2,3),(4,3,2),(2,2,2)]

sorts in ascending order according to first element

li.sort(key=sorts)
print(li)

sorts in descending order according to first element

li.sort(key=sorts, reverse=True)
print(li)

Output:
[(1,2,3),(2,2,2),(4,3,2)]
[(4,3,2),(2,2,2),(1,2,3)]

COPY METHOD:
=> We already discussed equals to (=) opeation, that does not copies that list into a new list.

new_list=old_list.copy()

Example:
z=[1,2,3,4]
x=z.copy()
print(z)
z.pop()
print(z)
print(x)
output:
[1,2,3,4]
[1,2,3]
[1,2,3,4]

=> We have another method that is slicing.

In these both cases, We can create a copy of the list that’s not affected there after.

Syntax:
new_list= old_list[: ]

Example:
z=[1,2,3,4]
x=z[:]
print(z)
z.pop()
print(z)
print(x)
output:
[1,2,3,4]
[1,2,3]
[1,2,3,4]

We have another approach that is using ‘list’ we can create a brand new list.
that is also a copy of passing list.

Syntax:
new_list= list(old_list)

Example:
z=[1,2,3,4]
x=list(z)
print(z)
z.pop()
print(z)
print(x)
output:
[1,2,3,4]
[1,2,3]
[1,2,3,4]

Python is free and easy to learn. Python is an interpreted language. Python is slower than Java programming language.

Comments

Popular posts from this blog

PYTHON TRINKET

FOR LOOP WITH ZIP FUNCTION IN PYTHON

Tuple