PYTHON LISTS
PYTHON LISTS
There are four collection data types in the Python programming language:
PYTHON LISTS
➢ Lists: In Python, a list is created by placing elements inside square brackets [],
separated by commas. A list can have any number of items and they may be of
different types (integer, float, string, etc.).
Example: Create a List:
a = ["apple", "banana", "cherry"]
List Items: List items are ordered, changeable, and allow duplicate values.List
items are indexed, the first item has index [0], the second item has index [1] etc.
• Ordered: When we say that lists are ordered, it means that the items have
a defined order, and that order will not change.If you add new items to a
list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in
general: the order of the items will not change.
Example
String, int and boolean data types:
Example
A list with strings, integers and boolean values:
Methods:
1. Len(): To determine how many items a list has, use the len() function:
Example: list1 = ["apple", "banana", "cherry"]
print(len(list1))
o/p= 3
2. append(): The append() method appends an element to the end of the list.
Syntax: list.append(elmnt)
Parameter Description
Example:
Add a list to a list:
3. clear():
Syntax: list.clear()
Example:
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
4. extend():
Syntax: list.extend(iterable)
Parameter Description
Example
p = (1, 4, 5, 9)
fruits.extend(p)
5. insert():
Syntax: list.insert(pos, elmnt)
Parameter Description
fruits.insert(1, "orange")
6. pop():
Syntax: list.( pos)
Parameter Description
pos Optional. A number specifying the position of the element you want to
remove, default value is -1, which returns the last item
Example:
fruits=['apple', 'banana', 'cherry']
a= fruits.pop(1)
7. remove():
Syntax: list.(elmnt)
Parameter Description
elmnt Required. Any type (string, number, list etc.) The element you
want to remove
Example:
fruits=['apple', 'banana', 'cherry']
fruits.remove("banana")
8. reverse():
Syntax: list.reverse()
Example:
fruits=['apple', 'banana', 'cherry']
fruits.reverse()
Parameter Description