Python Class4
Python Class4
List:
Syntax:
Variable = [value1,value2,value3,…]
Eg:
students = [“Ram”,”Siva”,”Mani”]
print(students) #[‘Ram’,’Siva’,’Mani’]
Eg:
emp =[“Selvam”,34,32000.00]
print(emp) # [‘Selvam’,34,32000.00]
List items can be accessed using index number. (Note: Index start with 0)
Eg:
print(emp[0]) #Selvam
Unlike other programming language, Python allow negative index. (-1 means last value, -2
means last before and so on)
Eg:
print(emp[-2]) #34
Range Behaviour:
Syntax:
variable[start_index : end_index]
Note: Here range start with start_index, but end in end_index-1.
Eg:
vowels= [‘a’, ’e’, ’i’, ’o’, ’u’]
print(vowels[2:4]) #[‘i’,’o’]
Eg:
print(vowels[:3]) # [‘a’, ’e’, ’i’]
print(vowels[1:]) # [‘e’, ’i’, ‘o’, ’u’]
Eg:
print(vowels[-4:-2] #[‘e’, ’i’]
Note: here -4 is included and -2 is excluded
Eg:
print(vowels[-3:] #[‘i’,’o’,’u’]
Eg:
print(vowels[:-1] #[‘a’,’e’,’i’,’o’]
In Python List in Mutable (Changeable), so we can change the value using index.
Eg:
vowels[1]=’E’
print(vowels) # [‘a’, ’E’, ’i’, ’o’, ’u’]
In Python to get number of items in the list, there is the predefined function called len().
Eg:
Print(len(vowels)) #5
Eg:
a = [1,2,3]
b = [4,5,6]
c = a+b
print(c) # [1,2,3,4,5,6]
To handle List in Python there are predefined methods available, they are
Eg:
a = list((1,2,3))
print(a) # [1,2,3]
Note: While creating list using list() function values should be given inside parenthesis