Lists
'''
1. Lists are ordered collection of data items.
2. They store multiple items in a single variable.
3. List items are separated by commas and enclosed within square brackets [ ].
4. Lists are mutable i.e. we can alter them after creation.
'''
list = [1, 2, 3]
print(list) #output = [1, 2, 3]
print(type(list)) #output = <class 'list'>
marks = [50, 60, 80]
print(marks) #output = [50, 60, 80]
print(type(marks)) #output = <class 'list'>
print(marks[0]) #output = 50
print(marks[1]) #output = 60
print(marks[2]) #output = 80
#Different data types can come under a single list.
data = [24, 2, 2002, "Sindhu", True]
print(data) #output = [24, 2, 2002, 'Sindhu', True]
'''
list Index:
Each item/element in a list has its own index.
This can be used to access any particular item in the list.
The first item has the index[0], second item has index[1] and so on.
#Example:
family = ("Prasad", "Arati", "Asish", "Sindhu")
[0] [1] [2] [3]
'''
'''
Accessing List Items:
We can access the list items by using its index with a square bracket syntax[ ].
'''
'''
Positive Indexing:
It refers to accessing elements in a sequence using non-negative integers, starting from 0 for the first element.
'''
#Example:
Fruits = ("Apple", "Banana", "Mango", "Grapes", "Orange")
print(Fruits[2]) #output = Mango
print(Fruits[4]) #output = Orange
print(Fruits[3]) #output = Grapes
#print(Fruits[5]) #output = tuple index out of range
'''
Negative Indexing:
It is also used to access the items, but from the end of the list.
The last item has index [-1], second item has index [-2] and so on.
'''
#Example:
Fruits = ("Apple", "Banana", "Mango", "Grapes", "Orange")
print(Fruits[-5]) #output = Apple
print(Fruits[-4]) #output = Banana
print(Fruits[-3]) #output = Mango
print(Fruits[-2]) #output = Grapes
print(Fruits[-1]) #output = Orange
'''
How to convert a negative index into positive index?
print(Fruits[-3]) #negative index
print(Fruits[len(Fruits)-3]) #positive index
print(Fruits[5-3]) #positive index
print(Fruits[2]) #positive index #output = Mango
'''
#We can check if a given item is present in the list or not by using "in" keyword.
if "Pineapple" in Fruits:
print("Yes")
else:
print("No") #output = No
if "Mango" in Fruits:
print("Yes")
else:
print("No") #output = Yes
if "priya" in "Sindhupriya":
print("Yes")
else:
print("No") #output = Yes
print(data) #output = [24, 2, 2002, 'Sindhu', True]
print(data[:]) #output = [24, 2, 2002, 'Sindhu', True]
print(data[1:]) #output = [2, 2002, 'Sindhu', True]
print(data[1:-1]) #output = [2, 2002, 'Sindhu']
print(data[1:4]) #output = [2, 2002, 'Sindhu']
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(numbers[1:10]) #output = (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(numbers[1:10:2])#output = (1, 3, 5, 7, 9)
print(numbers[1:10:3])#output = (1, 4, 7)
lst = [i*i for i in range(10)]
print(lst) #output = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
lst = [i*i for i in range(10) if i%2==0]
print(lst) #output = [0, 4, 16, 36, 64]
Comments
Post a Comment