python list and tuples 4 | Learn With Pirates
Chapater 4: Python List And Tuples
List In Python
Python list is used to store a set of values of any data type.
a = [5,6,7,8,] # Create a list with []
Output
[5, 6, 7, 8]
List Indexing
a = [5,6,7,8,]
# Access using index using a[0], a[1],
print(a[3])
Output
8
h = [77, "PIrates", True, 7.7] # create with any Data Type
print(h)
Output
[77, 'PIrates', True, 7.7]
Slicing In list:
# slicing in list
word = ["Pirates", "Learn", 66, "like", "tom"]
print(word[0:3])
print(word[-3:])
Output
['Pirates', 'Learn', 66]
[66, 'like', 'tom']
List Methods
l1 = [7, 8, 9, 10, 15, 16,]
print(l1)
l1.sort() # sorts the list
print(l1)
l1.reverse() # reverses the list
print(l1)
l1.append(45) # adds 45 at the end of the list
print(l1)
l1.insert(2, 199) # inserts 199 at index 2
print(l1)
l1.pop(2) # removes element at index 2
print(l1)
l1.remove(10) # removes 21 from the list
print(l1)
Output
[7, 8, 9, 10, 15, 16]
[7, 8, 9, 10, 15, 16]
[16, 15, 10, 9, 8, 7]
[16, 15, 10, 9, 8, 7, 45]
[16, 15, 199, 10, 9, 8, 7, 45]
[16, 15, 10, 9, 8, 7, 45]
[16, 15, 9, 8, 7, 45]
Tuples In Python
t = (1, 2, 4, 5) # Creating a tuple using ()
# How to create singal element tuple
t1 = () # Empty tuple
t1 = (7) # Wrong way to declare a Tuple with Single element
t1 = (7,) # Tuple with Single element
print(t1)
print(t[3]) # indexing tuple
output
5
t = (1, 2, 4, 5)
t[0] =55
print(t)
Output
TypeError: 'tuple' object does not support item assignment
Tuples methods
# consider this tuple
t = (1, 2, 4, 5, 6, 7,)
print(t.count(4)) #return number of time 4 in tuple
print(t.index(6)) #return index value of element
Output
1
4
Termination
If you Like this tutorial please share with your friend and family. I make an amazing tutorial in this blog. If you have any queries and question ask me in the comment section below.
No comments
Post a Comment