Tuesday, 17 September 2019

Built-in Methods for Python Lists

Python Lists - Built-in Methods


Let's learn some of the top built-in methods available for Python - lists.

Using append() with List

append() function can be used to add new items at the end of the list:
>>> cubes = [1, 8, 27, 64, 125]
>>> cubes
[1, 8, 27, 64, 125]

# append 216 at the end
>>> cubes.append(216)

# append cube of 7 at the end
>>> cubes.append(7 ** 3)
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

Using insert() with List

insert() function will add element to a list at specified position(index number). Check the following example:


>>> list1 = ['a', 'b', 'c']
>>> list1.insert(2, 'kp')
>>> list1
['a', 'b', 'kp', 'c']



Using extend() with List

Python extend() function combines two lists. Check the following example:


>>> myList1 = ['a', 'b', 'c']
>>> myList2 = [1, 2, 3]
>>> myList1.extend(myList2)
>>> print(myList1)
['a', 'b', 'c', 1, 2, 3]



Using pop() and remove() with List

pop() function will get the value of an item and remove it from the given list. pop() function needs index number of a list as a parameter. Check example of pop():


>>> list1 = ['a', 'b', 'c', 'd']
>>> list1
['a', 'b', 'c', 'd']
>>> list1.pop(2)
'c'
>>> list1
['a', 'b', 'd']

Using remove() with List

remove() function deletes an item from a list. remove() function needs actual value of an item as a parameter. Check following example of remove():

>>> list1 = ['a', 'b', 'c', 'd']
>>> list1.remove('d')
>>> list1
['a', 'b', 'c']

Using reverse() with List 
Reverse the elements of a given list.


>>> list1 = ['a', 'b', 'c', 'd']
>>> list1
['a', 'b', 'c', 'd']
>>> list1.reverse()
>>> list1
['d', 'c', 'b', 'a'] 

Using sort() with List 
Sort the elements of a given list alphabetically or numerically.


>>> list1 = ['c', 'b', 'a', 'd']
>>> list1
['c', 'b', 'a', 'd']
>>> list1.sort()
>>> list1
['a', 'b', 'c', 'd']


No comments:

Post a Comment