Python lists are containers to store a set of values of any type of data.
fruits = ["Apple", "me", "friend", 7, Flase]
Apple, me, friend are str type.
7 is int type
False is Bool type.
List Indexing : A list can be indexed just like a string.
l1=[7,9,"friend"]
l1[0] = 7
l2[1] = 9
l3[4] = Error
l1[0:2] = [7, 9] : List slicing
l1[0] = 7
l2[1] = 9
l3[4] = Error
l1[0:2] = [7, 9] : List slicing
List Methods :
l1 = [1,8,7,2,21,15]
l1.sort( ) : update the list to [1,2,7,8,15,21]
l1.reverse ( ) : updates the list to [15,21,2,7,8,1]
l1.append(8) : adds 8 at the end of the list
l1.insert (3,8) : this will add 8 at 3 index.
l1.pop(2) : will delete element at index 2 and return its value
l1.remove(21) : will remove 21 from the list.
l1.sort( ) : update the list to [1,2,7,8,15,21]
l1.reverse ( ) : updates the list to [15,21,2,7,8,1]
l1.append(8) : adds 8 at the end of the list
l1.insert (3,8) : this will add 8 at 3 index.
l1.pop(2) : will delete element at index 2 and return its value
l1.remove(21) : will remove 21 from the list.
Tuples in Python : A Tuple is an immolate data type in python. Means cannot change the data.
a = () : empty tuple
a = (1, ) : Tuple with only one element needs a comma.
a = (1,7,2) : tuple with more than one element
**Tuple elements cannot be altered or manipulated.
Tuple Methods:
a = (1,7,2)
1. a.count (1) : this will return number of times 1 occurs in a
2. a.index(1) : this will return index of first occurrence of 1 in a.
Programs :
1. #Lists
# Create a list using [ ]
a = [1, 2 , 4, 56, 6]
# Print the list using print() function
print(a)
# Access using index using a[0], a[1], a[2]
print(a[2])
# Change the value of list using
a[0] = 98
print(a)
# We can create a list with items of different types
c = [45, "cstechiie", False, 6.9]
print(c)
2. # List slicing
friends = ["cstechiie", "Tom", "Rohan", "Sam", "Dd", 45]
print(friends[0:4])
print(friends[-4:])
3. #List Methods
l1 = [1, 8, 7, 2, 21, 15]
print(l1)
# l1.sort() # sorts the list
# l1.reverse() # reverses the list
#l1.append(45) # adds 45 at the end of the list
# l1.insert(2, 544) # inserts 544 at index 2
# l1.pop(2) # removes element at index 2
l1.remove(21) # removes 21 from the list
print(l1)
4. #Tuples
# Creating a tuple using ()
t = (1, 2, 4, 5)
# t1 = () # Empty tuple
# t1 = (1) # Wrong way to declare a Tuple with Single element
t1 = (1,) # Tuple with Single element
print(t1)
# Printing the elements of a tuple
# print(t[0])
# Cannot update the values of a tuple
# t[0] = 34 # throws an error
5. # Tuple Methods