Online-Academy
Look, Read, Understand, Apply

Lists

List is an ordered and changeable collection of same data type or different data types

if __name__=="__main__":
    list1 = [100,200,30,50,60,77]
    print(list1)  #display list
    print(f"Length of List1: {len(list1)}")
    #list can be of any data type
    list2 = ["apple","papaya","cherry","mango","graph"]
    print(list2)  #display list
    list3 = [True,False,False,True,True,False]
    print(list3)
    #list can be of mixed data type
    list4 = [1,2,3,"apple",True,3.44]
    print(list4)
    print(f"Type of list4 is {type(list4)}")
    #creating list using list constructor
    list5 = list((33,44,55,'apple','Python','Conditional',True,33.44))
    print(list5)
    

We can check if element exists in list or not using in keyword:

    fruits = list(("apple","cricket","football","tennis",True,333,4.5))
    if "cricket" in fruits:
        print("cricket is in the list")
    

Accessing elements of list

List items can be access using index, list index starts from 0. We can be accessed from end also, to do so, negative indexing is used, -1 refers to last element, -2 refers to second last element and so on.

    print("Second element of list5 is: ",list5[1])
    print("Last element of list5 is: ",list5[-1])
    print("Second last element of list5 is: ",list5[-2])
    

We can access elements of list specifying range also. We have to specify start position and end position separated by : inside the square brackets. Element of Start position is included but element of end position is excluded. If start position is left out (not written) range will start from first element (0 position). If end position is not mentioned then range will go up to the end position.

    print(list2[2:5])
    print(list2[:4])
    print(list2[2:])
    

Negative indexes can be also specified in range, like -3:-1, -3 is third element from the end, -1 is last element. if range is given like: -3:-1 third and second element will be displayed but not last element as last position mentioned is excluded. List can contain duplicate elements.

    ll = [22, 33, 11, 333, 44, 22, 33, 4444, 55]
    print(ll[-3:-1])
    

Maninpulating list items

To change element of list, we have to specify the position of the element. If we want to change first element then we write list1[0] = value, if we have to change third element then we write list1[3] = value

    l1 = [22,33,44,55,66,11]
    print(l1)
    l1[0] = 100
    print(l1)
    

We can specify range of item values also, if we write list1[2:5] = ['a','b','c'], then third, fourth, and fifth elements will be changed.

    l1[2:5] = ['a','b','c']
    print(l1)
    

List can be sorted using sort method.

    l1 = ["honeybee","ant","bat","cat","bee","insect","lizard","housefly"]
    l1.sort()
    print("Sorted list",l1)
    l1.sort(reverse=True)
    print("List sorted in descending order: ",l1)
    print(l1)

    l1 = [33, 22, 44, 77, 45, 65, 11, 89, 3, 4, 100, 50]
    l1.sort()
    print("Sorted list", l1)
    

If we provide more element than the specified range then size of list will grow, adding new element,

    print(l1)
    l1[2:5] = [10,20,30,40,50] #here range is 2:5, only three elements, but 5 elements are provided, three elements of position 2nd, 3rd, and 4th will be changed and two more elements will be added.
    print(l1)
    

If fewer elements are provided than the range, new specified elements will be inserted, and the remaining elements will adjust accordingly.

    l1[2:5] = [101,201]
    print(l1)
    

We can insert new item without replacing existing element, using insert() method. We have to specify the position where we want to insert new element in insert() method.

    l1.insert(3,44)
    print(l1)
    

We can use append method to add element to the end of list

    l1.append(144)
    print(l1)
    

We can add new list to existing list using extendmethod. Any iterable iterable object (tuples, sets, dictionaries) can be appended to list using extend method

    l1.extend([-1,-4,-7,-7])
    print(l1)
    
Removing element from list

Remove method is used to remove element from list, value of the item to be removed is passed to remove method. If more than same value exists in list, then the first value appeared will be removes

    l1.remove(144)
    print(l1)
    l1.remove(-7)
    print(l1)
    
Using pop method to remove item at specified position from the list
    l1.pop(2)   #removing 3rd item
    print(l1)
    
Using del Keyword to remove item at specified position from the list

del keyword can be used to delete list completely. We can use clear method to remove items of list without removing list.

    del l1[5] # item 50 from list l1 will be removed
    print(l1)
    del l1
    #print(l1) will not work
    l1 = [] #creating empty list
    l1.extend([-1, -4, -7, -7])
    print(l1)
    l1.clear() #all items of list will be removed
    print(l1)   #displays empty list
    

Looping through list

We can use for or while loop to loop through the list

    l1 = [33,44,55,66,11,22,33,44,99,88]
    for l in l1:
        print(l,end=" ")
    print("\nLooping through list using for loop and range:")
    for i in range(len(l1)):
        print(l1[i],end=" ")

    while i < len(l1):
        print(l1[i],end=" ")
        i = i + 1
    
Copying list
We can copy one list to next by just using assignment operator like l2 = l1, as l2 only gets reference to l1. Changes like adding elements, replacing elements, removing elements in l1 will be automatically also be made in l2. To copy one list to another, we use copy() method. We can use list() method also to copy list.
    l3 = l1.copy()
    print("\nUsing copy\nL1: ",l1,"\nL3: ",l3)

    l1 = ['a','b','m','d','e','x']
    l3 = list(l1)  #list is constructor method
    print("\nUsing list\nL1: ", l1, "\nL3: ", l3)
    

Using Slice operator

We can use slice operator to make copy of list

    l3 = l1[:]
    print("\nUsing Slice\nL1: ", l1, "\nL3: ", l3)

    
We can join two lists using + operator also.
l2 = l1 + l3; print("\nJoining list using + operator:\n",l2)