List and List operations, iteration, traversal in Python

List is a most useful data collection in python. It acts as an Array and have associated functions to perform multiple operations in the List in Python.

Here we will elaborate the functionality and uses of List.

Lets start with a empty list creation and add String and Dictionary in to this:

listitems = []
listitems.append("Lucknow City")
listitems.append({'name':'John'})

Now we have variable listitems that have two different type of vaues. Let us test size and print these values.

len(listitems)

Output is: 2

len function in python is used to get the size of a List.

Now we will travers in the list.

for listitem in listitems:
    print(listitem)

Output: 

Lucknow City

{'name': 'John'}

Now it you need an index of value then enumerate the list first:

for index,listitem in enumerate(listitems):
    print(index,listitem)

Output: 

0 Lucknow City

1 {'name': 'John'}

Lets merge another list in the listitems.

listitems2 = ["Delhi","Kanpur"]
listitems.extend(listitems2)
print(listitems)

Now listitems will have 4 items.

Output:

['Lucknow City', {'name': 'John'}, 'Delhi', 'Allahabad']

Insert an element to a perticular position in the list:

listitems.insert(2,'Kanpur')

It this example value 'Kanpur' is inserted on 2nd position.

Remove an item by name form the List.

listitems.remove('noida')

You can delete items by index also:

del(listitems[2])

You can delete items by index range:

del(listitems[2:4])

Delete all items in list:

listitems.clear()

Pop item from list:

listitems.pop()

Pop item from list with index:

listitems.pop(2)

Sorting in the List:

listitems.sort()

Copy listitems into a new variable:

newlist = listitems.copy()

 

 


Keywords: