List in Python and operations

List is the collection of data items which are either of similar data type or dissimilar data types. A list is similar to array but in array we have only similar data items. In a list, we can have a different type of data items. So let’s start learning list in Python with various operations.

A list is represented with ” [ ] “(square braces).

Various Operations of List in Python

Example:

l=[1234,"Roy",'A',234.4]
print(l)

Output:

[1234, 'Roy', 'A', 234.4]

If we want to print a list without braces i.e; only elements in it

print(*l)
print(*l,sep=',')

Output:

1234 Roy A 234.4
1234,Roy,A,234.4

Here we can separate the elements by mentioning the separator at the end as shown above.

Appending/Adding elements to the list

Using the method ” append() ”¬† we can add the elements to the list.

When we use append the elements are added at the end of the list

l.append('Green Code')
print(l)

Output:

[1234, 'Roy', 'A', 234.4, 'Green Code']

If we want to append two lists

l1=[1,2,3,4]
l2=[5,6,7,8]
print(l1,l2)
l1.extend(l2)
print(l1,l2)

Output:

[1, 2, 3, 4] [5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8] [5, 6, 7, 8]

we use “extend()” as here we are extending the list l1 by adding l2 to it. If you use append() method¬† you’ll get an error.

Deletion operation on list

Using the following functions we can delete the elements in the list

  • pop() : removes the last element of the list
  • remove() : removes the specified element of the list
  • del() :deletes the element at specified index
a=[1,2,3,4,5,6]
a.remove(5)
print("remove : ",a)
del a[1]
print("del() : ",a)
a.pop()
print("pop() : ",a)

Output:

remove :  [1, 2, 3, 4, 6]
del() :  [1, 3, 4, 6]
pop() :  [1, 3, 4]

Leave a Reply

Your email address will not be published. Required fields are marked *