Python Lists Made Simple


What is a List in Python?
A list in Python is a built-in data type that can store multiple items of any data types such as integers, strings,tuples and even lists, under a single name. It is mutable i.e. you can add, edit, update and delete elements after the list is created.
Characteristics of Lists
i. Lists are ordered collection of objects i.e. position(index) of each item in a list is fixed and preserved.
ii. They are mutable i.e. you can add, edit, update and delete items after the list is created.
iii. They are heterogeneous i.e. they can store items of different data types in the same list.
iv. They are dynamic in nature i.e. they can grow or shrink in size.
v. They can contain any kind of objects in Python.
list1 = [print, max]
list1[0]("Hello")
print(list1[1]([1, 2, 3]))
#Output
#Hello
#3
Creating a List
- Empty list:
l=[]
print('Empty list:',l)
#Output
#Empty list: []
- List with Elements:
L=[1,2,3,4] #1D list
M=[1,2,3,[4,5]] #2D list
N=[[[1,2],[3,4]],[[12,14],[15,90]]] #3D list
O=[1,True,'Hii'] #Heterogeneous list
print(L,M,N,O,sep='\n')
#Output
# [1, 2, 3, 4]
# [1, 2, 3, [4, 5]]
# [[[1, 2], [3, 4]], [[12, 14], [15, 90]]]
# [1, True, 'Hii']
- Using list() Function:
print(list('Lemon'))
print(list(range(1,5)))
#Output
# ['L', 'e', 'm', 'o', 'n']
# [1, 2, 3, 4]
- From User Input
#input as a single line
l=input('Enter a string:').split()
print(l)
#input numbers and convert into integers
l=list(map(int,input('Enter numbers:').split()))
print(l)
#using list comprehension
l=[int(x) for x in input('Enter numbers:').split()]
print(l)
#using loops
l=[]
n=int(input('Enter the number of itmes in a list:'))
for i in range(n):
item=input('Enter an item:')
l.append(item)
print(l)
#Output
# Enter a string:i am a girl
# ['i', 'am', 'a', 'girl']
# Enter numbers:2 4 7
# [2, 4, 7]
# Enter numbers:20 68 29
# [20, 68, 29]
# Enter the number of itmes in a list:3
# Enter an item:hello
# Enter an item:1
# Enter an item:true
# ['hello', '1', 'true']
Accessing Items from a List
Once you have created a list, you can easily access an item (using indexing) or a part of list (using slicing).
#through indexing
L=[1,2,3,4]
print(L[0]) #positive indexing
print(L[-1]) #negative indexing
#through slicing
print(L[0:3])
print(L[-3:])
print(L[0::2])
#Output
# 1
# 4
# [1, 2, 3]
# [2, 3, 4]
# [1, 3]
Adding Items to a List
Since lists are mutable, you can add items at the end or at a specific position using the following methods:
append
extend
insert
append()
It adds a single item to the end of the list.
extend()
It adds multiple items (each item from another list) to the end of the list.
insert()
It adds one item at a specific position and shifts other items to the right.
l=[1,2]
l.append(5) #adds 5 at the end
print(l)
l.append([2,3]) #appends the list [2,3] as a single element
print(l)
print()
l.extend([6,7]) #adds 6 and 7 individually
print(l)
l.extend([[8,9]]) #adds [8,9] as a single element as it is inside another list
print(l)
l.extend('hi') #adds each character 'h' and 'i' individually as string is iterable
print(l)
l.extend(['hi']) #adds 'hi' as a single element as it is inside a list
print(l)
print()
l.insert(1,80) #inserts 80 at index 1 the rest shifts to the right
print(l)
#Output
# [1, 2, 5]
# [1, 2, 5, [2, 3]]
# [1, 2, 5, [2, 3], 6, 7]
# [1, 2, 5, [2, 3], 6, 7, [8, 9]]
# [1, 2, 5, [2, 3], 6, 7, [8, 9], 'h', 'i']
# [1, 2, 5, [2, 3], 6, 7, [8, 9], 'h', 'i', 'hi']
# [1, 80, 2, 5, [2, 3], 6, 7, [8, 9], 'h', 'i', 'hi']
Note the difference between append() and extend().
Editing Items in a List
In Python, you can update items in a list easily using indexing for single values and slicing for multiple values.
l=[1,2,3,4]
#editing with indexing
l[2]=20 #replaces the item at index 2 with 20
print(l)
#editing with slicing
l[1:3]=[18,19] #replaces the item at index 1 and 2 with 18 and 19
print(l)
#Output
# [1, 2, 20, 4]
# [1, 18, 19, 4]
Deleting Items from a List
Python offers several easy ways to delete items from a list, whether by index, value, or even the entire list at once, using the following methods:
del
remove
pop
clear
del
It removes the item at a specific index.
remove()
It removes the first occurrence of the given value.
pop()
It removes and returns the item at the given index. If any index is not given, then by default it deletes and returns the last item.
clear()
It deletes all the items of the list making it empty.
#deleting items from a list
l=[1,2,3,1,4,5,6,7,8]
print(l)
#del
del l[5] #using indexing
print (l)
del l[1:3] #using slicing
print(l)
#remove
l.remove(1)
print(l)
#pop
last=l.pop(1)
print(l)
print('The popped item',last)
last=l.pop()
print(l)
print('The popped item',last)
#clear
l.clear()
print(l)
#Output
# [1, 2, 3, 1, 4, 5, 6, 7, 8]
# [1, 2, 3, 1, 4, 6, 7, 8]
# [1, 1, 4, 6, 7, 8]
# [1, 4, 6, 7, 8]
# [1, 6, 7, 8]
# The popped item 4
# [1, 6, 7]
# The popped item 8
# []
Operations on a List
Python lists supports a wide range of operations that helps us to work with data more easily and efficiently. Here are some of the most common operation that you will use frequently:
Concatenation
Repetition
Membership
Loops
Concatenation
This operation uses a ‘+’ symbol to join two or more lists to form a new list.
l=[1,2,3,4,5]
m=[1,2,3,4,5,[6,7]]
print(l)
print(m)
print(l+m)
#Output
#[1, 2, 3, 4, 5]
#[1, 2, 3, 4, 5, [6, 7]]
#[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, [6, 7]]
Repetition
This operation joins multiple copy of the list using ‘*’ operator.
l=[1,2,3,4,5]
print(l*2)
#Output
#[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
Membership
This operation allows you to check whether an item is present in the given list or not using ‘in’ and ‘not in’ keywords.
l=[1,2,3,4,5]
m=[1,2,3,4,5,[6,7]]
print(5 in l)
print(6 in m)
print([6,7] in m)
#Output
# True
# False
# True
Loops
You can iterate through a list using loops (for and while both).
m=[1,2,3,4,5,[6,7]]
for i in m:
print(i)
print()
l=['apple','watermelon','orange']
while l:
print(l.pop())
#Output
# 1
# 2
# 3
# 4
# 5
# [6, 7]
# orange
# watermelon
# apple
Essential List Methods in Python
Python lists has built-in methods that helps us to add, remove, sort, delete and process the items in the lists more easily and efficiently. Some of them are listed below:
len()
It returns the number of items in a list. It works on heterogeneous lists as well.
min()
It returns the smallest item of the list.
max()
It returns the largest item of the list.
sorted()
It sorts the items of a list in ascending order and returns the sorted list. It does not change the original list.
l=[1,9,0,7,5,4,'Hii']
print(len(l))
l=[1,9,0,7,5,4]
print(max(l))
print(min(l))
print(sorted(l))
print(sorted(l,reverse=True))
l=['hi','i','am','fine']
print(max(l))
print(min(l))
print(sorted(l))
print(sorted(l,reverse=True))
#Output
# 7
# 9
# 0
# [0, 1, 4, 5, 7, 9]
# [9, 7, 5, 4, 1, 0]
# i
# am
# ['am', 'fine', 'hi', 'i']
# ['i', 'hi', 'fine', 'am']+
For min(), max() and sorted(), keep the list homogeneous to avoid errors.
count()
It counts the number of times an item appears in a list.
index()
It returns the first index where the item appears on list. If not found, it throws an error.
l=[1,9,0,7,5,1,4,0]
print(l.count(0))
print(l.index(1))
#print(l.index(10)) throws an error as 10 is not on the list
#Output
# 2
# 0
copy()
It creates a shallow copy of the list i.e. it creates a new list with the same items, but it is a new object in the memory.
l=[1,9,0,7,5,4,0]
print(l)
print(id(l))
l1=l.copy()
print(l1)
print(id(l1))
#Output
# [1, 9, 0, 7, 5, 4, 0]
# 2119121997312
# [1, 9, 0, 7, 5, 4, 0]
# 2119123608960
reverse()
It reverses the order of elements in a list in place (changes the original list).
sort()
It sorts a list in an ascending order by default and also permanently changes the list (that is the difference between sorted and sort).
l=[1,9,0,7,5,4,0]
l.reverse()
print(l)
l.sort()
print(l)
l.sort(reverse=True) #in descending order
print(l)
#Output
# [0, 4, 5, 7, 0, 9, 1]
# [0, 0, 1, 4, 5, 7, 9]
# [9, 7, 5, 4, 1, 0, 0]
Traversing a List
Traversing a List means accessing items of the list one by one to read, process or display them. There are three main ways to traverse a list:
- Item-wise
You can access the items directly which makes it simple and clean.
- Index-wise
You can access the items using their index which helps us to keep track of the position.
- Enumerate
This help us to know the index and the value of the item directly.
#item-wise
basket=['apple','banana','guava','pineapple']
for fruit in basket:
print(fruit)
#index-wise
l=[1,2,3,4]
for i in range(0,len(l)):
print(l[i])
#enumerate
fruits=['kiwi','apple','watermelon','banana']
for i,f in enumerate(fruits):
print(f'index {i}:item {f}')
#Output
# apple
# banana
# guava
# pineapple
# 1
# 2
# 3
# 4
# index 0:item kiwi
# index 1:item apple
# index 2:item watermelon
# index 3:item banana
Combining Lists Using zip()
Sometimes, we need to work with two or more lists together, for this Python provides a special function called zip() that lets you pair the elements from different lists into tuples. It returns a zip object, which is an iterator of tuples where the first item of each iterator are paired together, then second and so on.
zip() stops at the shortest list, the extra elements of the longer list is ignored.
l1=[1,2,3,4]
l2=[5,6,7,8,9]
print((zip(l1,l2)))
print(list(zip(l1,l2)))
l=[i+j for i,j in zip(l1,l2)] #adding two lists element-wise
print(l)
#Output
# <zip object at 0x00000259110626C0>
# [(1, 5), (2, 6), (3, 7), (4, 8)]
# [6, 8, 10, 12]
Conclusion
Python lists are one of the most powerful data type that you will use as a beginner. They are extremely versatile and useful in processing data and solving real-life problems, especially in data science. I hope this post helped you understand the basics of Python lists and made your learning journey easier.
What’s Next?
In this post, we have talked all about the basics of Python Lists.
In my next blog, I’ll dive into List Comprehension which is a powerful technique to create lists in a concise way.
Stay tuned!
Subscribe to my newsletter
Read articles from Ashuka Acharya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
