Collection In Python-
Python is providing a pre-defined library called collections.
How Many Types Of Collections In Python-
- 1) List
- 2) Tuple
- 3) Set
- 4) Dict
1) List –
- – Can store heterogeneous elements together.
- – Maintain insertion order.
- – Can store duplicate elements as well.
- – Can access the elements by indexing and by slicing.
Ex –
l = [10,20,30,40,50] list_data = [1, 2, 3] print(list_data) list_data = [1, 2, 'Python', 3] print(list_data) ##### Indexing ##### print(list_data[0]) print(list_data[1]) ##### Slicing ##### print(list_data[-2]) print(list_data[-1]) print(list_data[1:3]) print(list_data[1:]) print(list_data[:3]) Output- [1, 2, 3] [1, 2, 'Python', 3] 1 2 Python 3 [2, 'Python'] [2, 'Python', 3] [1, 2, 'Python']
Predefined/Existing Methods-
-
-
1) Index() –
Index is used to return the index value of a particular element.
- Return only first index of occurrence in case of duplicate elements.
-
-
-
2) Count-
Used to count the no. of occurrence of any particular element.
-
-
-
3) Append –
Used to add the elements at the last index.
-
-
-
4) Insert(Index_no, Val) –
Used to add the element at a particular location.
-
-
-
5) Pop()-
Used to remove the elements from last first (On the basis of LIFO(Last in first out)).
-
-
-
6) Pop(Index_no)-
Used to remove the elements from particular index.
-
-
-
7) Remove(Element) –
Used to remove a particular element.
-
-
-
8) Clear() –
Used to remove all the elements from list.
-
-
-
9) Sort() –
Used to sort the element.
-
-
-
10) Extend() –
Used to add more then one list into the another.
-
-
- – Python supports dynamic data type concept. Hence every element act like as an object.
- – int, float and string are immutable object in python.
- – list can also contain tuples as an element and vice versa is also possible.
-
-
Qsn:
Why all data types are immutable in python?
-
Ans:
because we don’t have primitive data type concept in python.
-
-
Notes-
list is mutable(Changeable) but list element can be either mutable(Changeable) or immutable(unchangeable).
- l = [10,20, [30,40]]
Ex-
list_data = [1 ,2,(3 ,4 ), 5, [6 ,7]] print(list_data) Output- [1, 2, (3, 4), 5, [6, 7]]