Python list
Python list
Allow Duplicate :
list = ["red", "green", "yellow", "orange", "purple"]
print(list)
List length:
list = ["red", "green", "blue"]
print(len(list))
List items:
l1 = ["red", "green", "blue"]
l2 = [4, 2, 6, 5, 3]
l3 = [True, True, False]
print(l1)
print(l2)
print(l3)
Access list:
list = ["red", "green", "blue"]
print(list[1])
Negative indexing:
list = ["orange", "yellow", "white"]
print(list[-1])
Range of indexing:
list = ["red", "green", "yellow", "white", "magenta", "voilet"]
print(list[2:5])
Range of negative index:
list = ["red", "green", "yellow", "orange", ]
print(list[-3:-1])
Append items:
list = ["red", "green", "blue"]
list.append("black")
print(list)
Insert items:
list = ["red", "green", "purple"]
list.insert(1, "white")
print(list)
Extend list:
list = ["red", "green", "blue"]
list1 = ["purple", "orange", "white"]
list.extend(list1)
print(list)
Loop list:
list = ["red", "green", "blue"]
for x in list:
print(x)
List comprehension:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
list = ["red","green","orange","white","black"]
for x in fruits:
if "a" in x:
list.append(x)
print(list)
Sort list alphanumerically:
list = ["red", "green", "blue", "white", "purple"]
list.sort()
print(list)
Numerically sort:
list = [100, 50, 65, 82, 23]
list.sort()
print(list)
Sort descending:
list = ["orange", "mango", "kiwi", "pineapple", "banana"]
list.sort(reverse = True)
print(list)
Extend list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Tuple: Tuples are used to store multiple items in a single variable.
tuple = ("red", "green", "blue")
print(tuple)
Length tuple:
tuple = tuple(("apple", "banana", "cherry"))
print(len(tuple))
Update tuple:
x = ("red", "green", "blue")
y = list(x)
y[1] = "purple"
x = tuple(y)
print(x)
Add items:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
tuple = tuple(y)
print(tuple)
’
Remove items:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
print(thistuple)
Multiply tuples:
fruits = ("red", "green", "blue")
mytuple = fruits * 2
print(mytuple)
Dictionary:
Dictionaries are used to store data values in key:value pairs.
dict = {
"NAME": "NARESH",
"ADDRESS": "HIRAN MAGRI",
"STATE": "RAJASTHAN"
}
print(dict)
Dict() Constructor:
dict = dict(name = "NEHA", age = 21, country = "INDIA")
print(dict)
Accessing items:
thisdict ={
"name": "NARESH",
"address":"hiran magri",
"state": "rajasthan"
}
x = thisdict["address"]
print(x)
Update dictionary:
thisdict = {
"name": "nikhil",
"address": "shanti nagar",
"year": 2003
}
thisdict.update({"year": 2004})
print(thisdict)
Add item dictionary:
dict ={
"name": "nitin",
"class": "mtech",
"semester": 4
}
dict["year"] = "2021"
print(dict)
p1 = {
"name" : "neha",
"year" : 2004
}
p2 = {
"name" : "soniya",
"year" : 2007
}
p3 = {
"name" : "kalpana",
"year" : 2011
}
person = {
"p1" : p1,
"p2" : p2,
"p3" : p3
}
print(person)