= ["apple", "banana"]
fruits print(fruits)
print(type(fruits))
print(fruits[1])
['apple', 'banana']
<class 'list'>
banana
A collection of items, in python, is refered to as a list
. A list can have elements of same data type or multiple data types. A list is denoted by square brackets ([]
). The indexing of elements in a list starts from zero. To access an element by its index we can specify index in square brackets after the list name. Slicing of lists can be performed as well.
= ["apple", "banana"]
fruits print(fruits)
print(type(fruits))
print(fruits[1])
['apple', 'banana']
<class 'list'>
banana
Lists are mutable data type i.e. the contents of the collection can be changed. The append
and extend
functions adds an element or a collection of elements to a list. To add an element at a specified position within the list, the insert
function can be used.
"mango")
fruits.append(print(fruits)
print(len(fruits))
['apple', 'banana', 'mango']
3
= ["apple", "banana"]
fruits = ["pineapple","cherry"]
fruits2 #adding a list using append
fruits.append(fruits2) print(fruits)
print(len(fruits))
= ["apple", "banana"]
fruits = ["pineapple","cherry"]
fruits2 #adding a list using extend
fruits.extend(fruits2) print(fruits)
print(len(fruits))
['apple', 'banana', ['pineapple', 'cherry']]
3
['apple', 'banana', 'pineapple', 'cherry']
4
1,"grapes")
fruits.insert(print(fruits)
['apple', 'grapes', 'banana', 'pineapple', 'cherry']
# slicing
print(fruits[1:4])
['grapes', 'banana', 'pineapple']
To remove the last element from a list, pop
function can be used. It returns a the last element and the original list is shortened by one element. To remove an element by its name use the remove
function. Note that if a list has duplicate elements then the remove
function would delete only the first occurance of that element.
= fruits.pop()
last_fruit print(fruits)
print(last_fruit)
['apple', 'banana', 'pineapple']
cherry
"banana")
fruits.remove(print(fruits)
['apple', 'pineapple']
There are some useful functions available to manupulate lists. These functions act in place i.e. these functions do not return anything and just modifies the original list.
= ['apple', 'banana', 'mango', 'pineapple', 'cherry', 'banana']
fruits print(fruits.count("banana"))
fruits.reverse()print(fruits)
fruits.sort()print(fruits)
=True)
fruits.sort(reverseprint(fruits)
2
['banana', 'cherry', 'pineapple', 'mango', 'banana', 'apple']
['apple', 'banana', 'banana', 'cherry', 'mango', 'pineapple']
['pineapple', 'mango', 'cherry', 'banana', 'banana', 'apple']
Quiz: Given a list nums=[1,2,3,4,5]. Write a code to print 4.
= [1,2,3,4,5]
nums print(nums[3])