List Manipulation In Python
List is a collection of values or an ordered sequence of values /items.
The items in a list can be of any type such as string, integer, float or even a list.
Elements of a list are enclosed in Square brackets[] ,separated by commas.
List are mutable.i.e., values in the list can be modified
L1=[1,2,5,4]
L1=[1,2.25,”python”,”10+j12”,[10,20,30],245]
List are heterogeneous.
CTM: A list is a collection of comma-separated values (items) within square brackets.items in a list need not be of the same type.
1.Declaring/Creating List
Syntax:
<List_Name>=[]
For example:
L=[]
Initialization/blank /no values/empty list
2.List types and examples:
1. Empty List
2. Long Lists
3. Nested Lists
For Example:
list=[10,20,30,40]
#list of integers
list=[“Deep”,450,30.4,”python”,-200]
# list with elements of different data types.
list= [‘A’,’E’,’I’,’O’,’U’]
#list of characters
List=[“Delhi”,”Mumbai”]
#list of 2 string
List=[3,4,[5,6,7],8,9,10]
#list containing another list as an elements. i.e Nested list
List=[0,1,2,3,4,5,6,100,23,45,65,33,45,6,7,82,90,100,23,453,22,-32,343,-20]
3.Creating a List from an existing sequence
Syntax:
<new_list_name>=list(sequence)
For example:
>>> list1=list()
>>> l1=list("computer")
>>> l1
['c', 'o', 'm', 'p', 'u', 't', 'e', 'r']
>>> list1=list()
>>> type(list1)
<class 'list'>
>>> list1=list()
4.An empty with function list()
>>> list1
[]
>>>
5.Creating a list through user input using list() method.
Syntax:
>>> l1=list(input("Enter a list of elements"))
Enter a list of elements 10,20,30,40
>>> l1
[' ', '1', '0', ',', '2', '0', ',', '3', '0', ',', '4', '0']
>>> l1=list(input("Enter a list of elements"))
Enter a list of elements hi python
>>> l1
[' ', 'h', 'i', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> l1=list(input("Enter a list of elements"))
Enter a list of elements102030
>>> l1
['1', '0', '2', '0', '3', '0']
6.Creating from an existing list:
For example:
>>> l1=[10,20,30,40,50,60,70]
>>> l2=l1[:]
>>> l2
[10, 20, 30, 40, 50, 60, 70]
>>> l3=l2[1:4]
>>> l3
[20, 30, 40]
>>> l4=l1
>>> l4
[10, 20, 30, 40, 50, 60, 70]
4. Accessing List Elements:
L1=[10,20,30,40,50,60]
Positive Index | 0 | 1 | 2 | 3 | 4 | 5 |
L1 | 10 | 20 | 30 | 40 | 50 | 60 |
Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
>>> l1=[10,20,30,40,50,60]
>>> l1[3]
40
>>> l1[-3]
40
>>> l1[0]
10
>>> l1[-1]
60
>>>
>>> l1[7]
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
l1[7]
IndexError: list index out of range
7.Traversing a List:
Accessing each elements of a list.This can be done with the help of for loop and while loop.
Syntax:
list=[‘l’,’e’,’a’,’r’,’n’]
for i in list:
print(i)
8.Using range of function
For example:
list=[‘l’,’e’,’a’,’r’,’n’]
n=len(list)
for i in range(n):
print(list[i])
print(“Total number of characters”,n)
9.Comparing Lists:
L1=[10,20,30,40,50]
L2=[10,20,30,40,50]
L1==L2
>>> L1==L2
True
>>> L3=[1,2,3]
>>> L1==L3
False
>>> L1>L3
True
>>> L3>L1
False
>>> L2<L3
False
>>>
0 Comments