List in Python

What are list in Python? 

A list is a sequence of elements or an array placed in a square bracket '[]'.


A Python list can have mixture of data types, i.e. integers, floating point numbers, boolean values, strings...  All can be put together into one list.


That means Python list is not data type specific.


Python list are mutable (it can be modified).


How to access the element of a Python list? 

Index number's are used to access the element of a list.


Initialization of Python list 

List in Python can be initialized by 2 ways-

  • Using square bracket '[]'.
  • Using 'list()' build-in function.


Initializing Python list using square brackets

Each element of the sequence is separated by comma and are placed inside the square bracket.


Program 

>>> a = [9, 5.9, True, "Hello world!"]
>>> print(a)
[9, 5.9, True, 'Hello world!']


Initialization of Python list using build-in 'list() ' function

For initialization of Python list using build-in 'list()' function, put the sequence in the square brackets and give this as an argument to the 'list()' function.


Program

>>> a = list([1, 2.2, False, "H!"])
>>> print(a)
[1, 2.2, False, 'H!']


Creating an empty Python list

Don't put any element into the square brackets and don't provide any argument to the build-in 'list()' function, to create an empty Python list.

Program


>>> a = []
>>> print(a)
[]
>>> b = list()
>>> print(b)
[]



List operations in Python

Here you will get to know, what operations you can perform with the Python list.


Accessing an element

Use the index number of that element to access it.


Python list indexing start with 0, i.e. the first element will have '0' index number - second will have '1' index number - and soo on .


Program

>>> milk = ['paneer', 'ghee', 'cream', 'Lassi', 'curd']
>>> milk[0]
'paneer'
>>> milk[3]
'Lassi'
>>> # If we specify the index number out of range, then...
>>> milk[9]
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    milk[9]
IndexError: list index out of range


Accessing with negative indexing

We can also access an element using a negative number.


Index number '-1' refers to the last element of the list, '-2' pointes to the second last element of the list and soo on.


This is used when you want to access the element from the last.


Program

>>> milk[-1]
'curd'
>>> milk[-5]
'paneer'
>>> milk[0]
'paneer'


List slicing in Python

Selection of particular range of elements in a list, has the following format


list_name[starting index: ending index]


Program


>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[2:8]
[2, 3, 4, 5, 6, 7]


By not specifying the starting index, slicing will start from the first element.

Program


>>> numbers[:5]
[0, 1, 2, 3, 4]


By not specifying the ending index, the elements will get selected till the end of the list.

Program


>>> numbers[3:]
[3, 4, 5, 6, 7, 8, 9]



By not specifying the both starting index and ending index, then all the elements get selected.

Program

>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


We can also specify the interval (steps)


list_name[starting index: ending index: steps]

Program


>>> numbers[2:8:2]
[2, 4, 6]
>>> numbers[::3]
[0, 3, 6, 9]


Range selection with negative indexing 

Negative indexing is useful when you want to select the elements from the end of the list.


Program

>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[-6:-1]
[4, 5, 6, 7, 8]
>>> # Here the -6 is the index of element '4'.



Changing the element of a list

Changing an element of a list is possible, by referring to it's index number.

Program

>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[0] = -1
>>> print(numbers)
[-1, 1, 2, 3, 4, 5, 6, 7, 8, 9]



Length of a list

Use 'len()' built-in function to know the length of a list.


Program

>>> numbers = [-1, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(len(numbers))
10


Append/add element to the list

To add an element to a list use 'append()' method.


Which will add the element at the end of a list.


The element is passed as an argument to the 'append()' method.


Program

>>> numbers.append(10)
>>> numbers
[-1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers.append('string goes like this')
>>> print(numbers)
[-1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'string goes like this']


Python list insert() method

To add an element anywhere in a list, by specifying the index number.


The insert() method takes 2 arguments.

  1. Index
  2. Object/value

The object gets inserted at the index number we specify, and all other elements after it (elements at the right side) get shifted.

Program

>>> a = [0, 2, 3, 4, 5]
>>> a.insert(1, 1)
>>> print(a)
[0, 1, 2, 3, 4, 5]
>>> a.insert(-1, 6)
>>> print(a)
[0, 1, 2, 3, 4, 6, 5]


Removing an element from a list

To remove an element from a list, there are more than one methods.

  • Using remove() method.

    • The element that has to be removed is passed as an argument to the remove() method.
Program

>>> milk = ['paneer', 'ghee', 'cream', 'Lassi', 'curd']
>>> milk.remove('curd')
>>> print(milk)
['paneer', 'ghee', 'cream', 'Lassi']


  • Using pop() method.

    • The index number of an element (the element which we have to remove) is passed as an argument to the pop() method.
Program

>>> milk.pop(0)
'paneer'
>>> print(milk)
['ghee', 'cream', 'Lassi']


    • If the index number is not specified then it will remove the last element of the list.
Program

>>> milk.pop()
'Lassi'
>>> print(milk)
['ghee', 'cream']


  • Using del keyword.

    • An element is removed by specifying the index of a list.
Program

>>> milk = ['paneer', 'ghee', 'cream', 'Lassi', 'curd']
>>> del milk[2]
>>> print(milk)
['paneer', 'ghee', 'Lassi', 'curd']


Clearing a list

The clear() method, makes the list empty.

Program

>>> milk = ['paneer', 'ghee', 'cream', 'Lassi', 'curd']
>>> print(milk)
['paneer', 'ghee', 'cream', 'Lassi', 'curd']
>>> milk.clear()
>>> print(milk)
[]

Deleting a list

The del keyword will delete a list from the program.


Program

>>> milk = ['paneer', 'ghee', 'cream', 'Lassi', 'curd']
>>> print(milk)
['paneer', 'ghee', 'cream', 'Lassi', 'curd']
>>> del milk
>>> print(milk)
Traceback (most recent call last):
  File "<pyshell#65>", line 1, in <module>
    print(milk)
NameError: name 'milk' is not defined
>>> 


Joining two or more list

Make use of '+' operator to join the list.

Program


>>> a = [0, 1, 2, 3, 4]
>>> b = [5, 6, 7, 8, 9]
>>> c = a + b
>>> print(c)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


Joining more lists...


>>> a = [0, 1, 2, 3, 4]
>>> b = [5, 6, 7, 8, 9]
>>> st = ['a', 'b', 'c']
>>> k = a + b + st
>>> print(k)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c']


>>> alpha = [1, 2, 3]
>>> beta = [4, 5, 6]
>>> alpha += beta
>>> print(alpha)
[1, 2, 3, 4, 5, 6]
>>> print(beta)
[4, 5, 6]


Python list extend() method

Extend a list by appending elements form the sequence.


Program

>>> a = [1, 2, 3]
>>> print(a)
[1, 2, 3]
>>> a.extend([4, 5, 6])
>>> print(a)
[1, 2, 3, 4, 5, 6]
>>> b = [0, 0, 0]
>>> a.extend(b)
>>> print(a)
[1, 2, 3, 4, 5, 6, 0, 0, 0]
>>> a.clear()
>>> a.extend("Hello world!")
>>> print(a)
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']



List multiplication

The list gets repeated, to the number we specify.


Program

>>> a = [1] * 5
>>> a
[1, 1, 1, 1, 1]
>>> b = [1, 2, 3]
>>> b *= 3
>>> print(b)
[1, 2, 3, 1, 2, 3, 1, 2, 3]



Copy a list

The command 'list1 = list2' will not work because, the changes made in list1 will automatically be made in list2. As both the lists will have the same memory location.


Program

>>> a = [0, 1, 2, 3, 4]
>>> copyA = a
>>> print(a)
[0, 1, 2, 3, 4]
>>> print(copyA)
[0, 1, 2, 3, 4]
>>> copyA.append(10)
>>> print(copyA)
[0, 1, 2, 3, 4, 10]
>>> print(a)
[0, 1, 2, 3, 4, 10]
>>> id(copyA) == id(a)
True


Use the 'copy()' method to make a copy of a list.


Program

>>> a = [1, 2, 3, 4, 5]
>>> copyA = a.copy()
>>> print(a)
[1, 2, 3, 4, 5]
>>> print(copyA)
[1, 2, 3, 4, 5]
>>> copyA.append(10)
>>> print(copyA)
[1, 2, 3, 4, 5, 10]
>>> print(a)
[1, 2, 3, 4, 5]


Python list reverse() method

Reverse the order of a list.

Program


>>> a = [0, 1, 2, 3, 4, 5]
>>> print(a)
[0, 1, 2, 3, 4, 5]
>>> a.reverse()
>>> print(a)
[5, 4, 3, 2, 1, 0]



Python list count() method

Returns the number of occurrence of value in a list.


Program


>>> b = [1, 2, 1, 3, 5, 2, 1]
>>> b.count(1)
3



Python list index() method

Return index of an element, in a list.


If an element is repeated, then the index of first repeated element is returned.


Program

>>> animals = ['dog', 'cat', 'tiger', 'cow', 'puma']
>>> animals.index('dog')
0
>>> animals.index('cow')
3



>>> num = [0, 5, 1, 3, 5, 6, 8, 5, 3]
>>> num.index(5)
1
>>> num.index(5)
1
>>> 



Python list sort() method

Syntax / format :-  sort(key=None, reverse=False).


The key and reverse are the keyword arguments.


When key is provided with a function, according to which sorting is done, by applying the function once to each list item . Default is set to None.


When reverse = False, then list is sorted in ascending order. And when reverse = True, then list is sorted in descending order. Default is False.


Program

>>> num = [6, 0, 8, 5, 99, 69, 3, 5, 9]
>>> num.sort()
>>> print(num)
[0, 3, 5, 5, 6, 8, 9, 69, 99]
>>> num.sort(reverse=True)
>>> num
[99, 69, 9, 8, 6, 5, 5, 3, 0]





Conclusion

List is the collection of objects, which are ordered and mutable.

In this we have learned all the methods available with list.





Previous                          Next

If you have any query, feel free to ask.

إرسال تعليق

If you have any query, feel free to ask.

Post a Comment (0)