Python List

Python tutorial for List from scratch

The Python list is a general data structure widely used in python programs. They are both mutable and sequence data type that allows them to be indexed and sliced. The list can contain different types of objects , including other list objects.

Working with List

# creating a list
a = [10, 20, 30, 40, 50]
print(a)

#Output
[10, 20, 30, 40, 50]
# to add a new element in the list append method is used
a.append(60)
a.append(70)
a.append(80)
print(a)

#Output
[10, 20, 30, 40, 50, 60, 70, 80]
# to append another list
b = [90, 100]
c = ['Aman', 'Kharwal']
a.append(c)
a.append(b)
print(a)

#Output
[10, 20, 30, 40, 50, 60, 70, 80, ['Aman', 'Kharwal'], [90, 100]]
# to add elements of one list to another list
a = [10, 20, 30, 40, 50]
print(a)
b = [60, 70]
a.extend(b)
print(a)

#Output
[10, 20, 30, 40, 50, 60, 70]

Insert Function

insert(index, value)- Inserts value just before the specified index. You must know that the index in programming starts from 0 and not 1.

#insert 0 at position 0
a.insert(0, 0)
print(a)

#Output
[0, 10, 20, 30, 40, 50, 60, 70]

# insert 15 at position 2
a.insert(2, 15)
print(a)

#Output
[0, 10, 15, 20, 30, 40, 50, 60, 70]

Pop function

pop(index)-It removes the item at index. With no argument it removes the last element of the list.

# removing 2nd element from list
a.pop(2)
print(a)

#Output
[0, 10, 15, 20, 30, 40, 50, 60, 70]
[0, 10, 20, 30, 40, 50, 60, 70]

# removing last element from list
a.pop()
print(a)

#Output
[0, 10, 20, 30, 40, 50, 60, 70]
[0, 10, 20, 30, 40, 50, 60]

Remove Function

remove(value)- removes the specified value. It do not work on the index, it works on the value.

# remove
a.remove(30)
print(a)

#Output
[0, 10, 20, 40, 50, 60]

Reverse Function

reverse()- Reverses the list.

# reverse
a.reverse()
print(a)

#Output
[60, 50, 40, 20, 10, 0]

Count Function

count(value)- Counts the number of occurrences of some value in the list.

# count
a = ["John", "Aman", "John", 23, "John"]
print(a.count("John"))

#Output
3

Creating a list with Range function

# range
a = list(range(10))
print(a)

#Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Accessing list values

Python lists are 0-indexed, and act like arrays in other languages

a = [10, 20, 30, 40, 50]
print(a[2])
print(a[0])
print(a[-1]) # gives last item

#Output
30
10
50

Previous||Next Chapter

Leave a Reply