Python list operations

Python list operations

Instructor-svgAl-Mamun Sarkar
Mar 24 , 2020

The list is used to store a list of values in a single variable. Although there are some differences you can call it an array. 

Create a List:

names = ["Jone", "Doe", "Jems"]

 

Create List using list() Constructor:

names = (("Jone", "Doe", "Jems"))

 

Print the list:

print(names)

You can access items on the list by its index. Keep in mind that the index starts from 0. So first element is names[0]. 

 

Print Element:

print(names[0])
print(names[1])
print(names[2])

 

Updating Elements value:

names[0] = "Mamun"
names[1] = "Sarkar"

 

A list can have multiple types of data:

student = ["Jone Doe", 10, True, 3.5, "male"]

 

Getting the length of the List:

len(names)

 

Negative Indexing:

We can access the list by using Negative Indexing. -1 for the last item and -2 for the second last item and so on. 

print(names[-1])
print(names[-2])

 

Use Range of Indexes:

l = ['one', 'two', 'three', 'four', 'fine', 'six']
print (l[1:3])
print (l[:4])
print (l[2:])

Output:

['two', 'three']
['one', 'two', 'three', 'four']
['three', 'four', 'fine', 'six']

 

Use Negative Indexes in Range: 

l = ['one', 'two', 'three', 'four', 'fine', 'six']
print (l[-3:-1])
print (l[:-2])
print (l[-4:])

Output:

['four', 'fine']
['one', 'two', 'three', 'four']
['three', 'four', 'fine', 'six']

 

Check if an item is present in the list:

print("two" in l)

It will return True if the item present otherwise returns False.

 

Create Nested List:

items =[
    [1, 2, 3, 4],    
    [4, 5, 6, 7],    
    ['One', 'Two', "Three"]    
]
print(items[0][0])
print(items[2][1])
print(items[1][3])

Output:

1
Two
7

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram