Python Lists with example

Basically, Python Lists are of three types as given below

  • Ordered:- In the ordered list, items are arranged in a fixed order that can not be changed. If a new item is added, it will be placed at the end of the list values.
  • Changeable:- A list is changeable which means we can change the order of items in the list, add new items or remove items from the list variable.
  • Allow Duplicates:- We can add duplicate values in a list and the same values are accessed according to the index as the index starts from the position ‘0’.
carlist = ["Maruti","Volvo","BMW","Toyota"] 
print(carlist)
mylist = ["xyz",23,"abc",10.5,False] 
print(mylist)
mylist = [1,2,3,4,4] 
print(mylist)
mylist = [1,2,3,4,5] 
print(len(mylist))
mylist = list(("maruti","volvo","BMW","Toyota")) 
print(mylist)
mylist = ["maruti","volvo","BMW","Toyota"] 
print(mylist[2])
  • ‘-1’ indicates the last item from the list
  • ‘-2’ indicates the second last item from the list
  • ‘-3’ indicates the third last item from the list
mylist = ["maruti","volvo","BMW","Toyota"] 
print(mylist[-3])
mylist = ["maruti","volvo","BMW","Toyota"] 
print(mylist[1:3])
carlist = ["maruti","volvo","BMW","Toyota"] 
if "BMW" in carlist:
print("yes. BMW is in the list")
carlist = ["maruti","volvo","BMW","Toyota"] 
carlist[1] = "Scorpio"
print(carlist)
carlist = ["maruti","volvo","BMW","Toyota"] 
carlist[1:3] = ["Scorpio","Bolero"]
print(carlist)
carlist = ["maruti","volvo","BMW","Toyota"] carlist.append("Marcetis") 
print(carlist)
carlist = ["maruti","volvo","BMW","Toyota"] carlist.insert(1,"Marcetis") 
print(carlist)
carlist = ["maruti","volvo","BMW","Toyota"] 
bykelist = ["Honda","Bazaz","TVS"]
carlist.extend(bykelist)
print(carlist)
carlist = ["maruti","volvo","BMW","Toyota"] 
carlist.remove("volvo")
print(carlist)
carlist = ["maruti","volvo","BMW","Toyota"] 
carlist.pop(2)
print(carlist)
carlist = ["maruti","volvo","BMW","Toyota"] 
del carlist[1]
print(carlist)
carlist = ["maruti","volvo","BMW","Toyota"] 
newcarlist = []
for x in carlist:
if 'o' in x:
newcarlist.append(x)
print(newcarlist)
newcarlist = [x for x in carlist if 'o' in x] 
print(newcarlist)
carlist = ["maruti","volvo","BMW","Toyota"] 
carlist.sort()
print(carlist)
carlist = ["maruti","volvo","BMW","Toyota"] 
carlist.sort(reverse = True)
print(carlist)
carlist = ["maruti","volvo","BMW","Toyota"] 
newcarlist = carlist.copy()
print(newcarlist)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bipsmedium

Bipsmedium

Hi, This is Biplab and I am web developer well versed in PHP and other open source technologies. I am here to share my experience with the community.