Python List

In Python, lists are:

  • ordered
  • indexed (indices start at 0)
  • mutable
  • heterogeneous (items in a list can be of different types)
  • written as a list of comma-separated values between square brackets

1. Creating a List

Following are the examples to create a list in Python.

# empty list
empty = []

# list of strings
listOfSubjects = ['physics', 'chemistry', "mathematics"]

# list of numbers
listOfIds = [0, 1, 2, 3, 4]

# list of mixed types
miscList = [0, 'one', 2, 'three']

# list of lists
lists = [ ['A', 'B', 'C'], ['D', 'E', 'F'] ]

2. Adding items in List

  • To add an item to the end of the list, use the append(item) method.
  • To add an item at specific index position, use the insert(index, item) method. If index is greater than list size, item is added at the end of the list. No error is thrown in this case.
charList =  [] #empty list

charList.append("a")	
charList.append("b")

print (charList)		# ['a', 'b']

charList.insert(3, "c") 

print (charList)		# ['a', 'b', 'c']

charList.insert(10, "d")	# No error 

print (charList)	# ['a', 'b', 'c', 'd']

3. Accessing items in List

  • To access the items in a Python list, use the square brackets in slicing syntax or array indices to get a single item or range of items from the List.
  • The index values passed can be positive or negative both.
  • A negative index value means reverse counting elements from the end of the list.
  • list [m : n] returns sublist starting at index m (included) and ending at index n (not included).
    1. If m is not provided then its value is assumed to be zero.
    2. If n is not provided then range is selected till size of the list.
numList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print( numList[0] )			# 0

print( numList[1:5] )		# [1, 2, 3, 4]

print( numList[ : 3] )		# [0, 1, 2]

print( numList[7 : ] )		# [7, 8, 9]

print( numList[-8:-5] )		# [2, 3, 4] - Reverse traversal

4. Modifying a List

To change any specific it/ in the list, use item’s index location and assign a new value to it.

charList =  ["a", "b", "c"]

charList [2] = "d"

print (charList)	# ['a', 'b', 'd']

5. Iterating a List

We can loop through a list in Python by using a for loop.

Be very careful about in indentation while writing code in Python. Indentations refer to scope of the code block, and a wrong indentation will be make the whole program incorrect.
charList =  ["a", "b", "c"]

for x in charList:
	print(x)

# a
# b
# c

6. Check if a given item exists in the List

Use the 'in' keyword to determine if a specified item is present in a list.

charList =  ["a", "b", "c"]

if "a" in charList:
	print("a is present")	# a is present


if "d" in charList:
	print("d is present")
else:
	print("d is NOT present")	# d is NOT present

7. List size

Use the len() function to find the length or size of a given List.

charList =  ["a", "b", "c"]

x = len (charList)

print (x)	# 3

8. Removing item from the List

To remove an item from the list, use one of the four methods. We can appropriate method for deletion based on what information we have about the item to be deleted.

  • remove() – Removes item by its value
  • pop() – Remove item from end of the List; or from a specified index position.
  • clear() – Remove all items from the List.
  • del – This keyword need the index of the item to be deleted inside the List.

8.1. remove()

It searches the specified item in the list and removes it by it’s value.

charList =  ["a", "b", "c"]

charList.remove("c")	

print (charList)		# ['a', 'b']

8.2. pop()

It removes the specified item by it’s index. If index is not provided, it removes the last item from the list.

charList =  ["a", "b", "c", "d"]

charList.pop()			# removes 'd' - last item

print (charList)		# ['a', 'b', 'c']

charList.pop(1)			# removes 'b'

print (charList)		# ['a', 'c']

8.3. clear()

It empties the list.

charList =  ["a", "b", "c", "d"]

charList.clear()	

print (charList)		# []

8.4. del keyword

It can be used to remove an item from list by it’s index. We can use it to delete the whole list as well.

charList =  ["a", "b", "c", "d"]

del charList[0]	

print (charList)		# ['b', 'c', 'd']

del charList

print (charList)		# NameError: name 'charList' is not defined

9. Joining two Lists

We can join two given lists in Python using either "+" operator or extend() function.

charList = ["a", "b", "c"]
numList	= [1, 2, 3]

joinedList = charList + numList

print (joinedList)	# ['a', 'b', 'c', 1, 2, 3]

charList.extend(numList)

print (charList)	# ['a', 'b', 'c', 1, 2, 3]

10. List Methods

10.1. append()

Adds an element at the end of the list.

charList =  ["a", "b", "c"]

charList.append("d")

print (charList)	# ["a", "b", "c", "d"]

10.2. clear()

Removes all the elements from the list.

charList =  ["a", "b", "c"]

charList.clear()

print (charList)	# []

10.3. copy()

Returns a copy of the list.

charList =  ["a", "b", "c"]

newList = charList.copy()

print (newList)	# ["a", "b", "c"]

10.4. count()

Returns the number of elements with the specified value.

charList =  ["a", "b", "c"]

x = charList.count('a')

print (x)	# 1

10.5. extend()

Add the elements of a list to the end of the current list.

charList = ["a", "b", "c"]
numList	= [1, 2, 3]

charList.extend(numList)

print (charList)	# ['a', 'b', 'c', 1, 2, 3]

10.6. index()

Returns the index of the first element with the specified value.

charList =  ["a", "b", "c"]

x = charList.index('a')

print (x)	# 0

10.7. insert()

Adds an element at the specified position.

charList =  ["a", "b", "c"]

charList.insert(3, 'd')

print (charList)	# ['a', 'b', 'c', 'd']

10.8. pop()

Removes the element at the specified position or end of the list.

charList =  ["a", "b", "c", "d"]

charList.pop()			# removes 'd' - last item

print (charList)		# ['a', 'b', 'c']

charList.pop(1)			# removes 'b'

print (charList)		# ['a', 'c']

10.9. remove()

Removes the item with the specified value.

charList =  ["a", "b", "c", "d"]

charList.remove('d')

print (charList)		# ['a', 'b', 'c']

10.10. reverse()

Reverses the order of items in the list.

charList =  ["a", "b", "c", "d"]

charList.reverse()

print (charList)		# ['d', 'c', 'b', 'a']

10.11. sort()

Sorts the given list in ascending order by default.

charList =  ["a", "c", "b", "d"]

charList.sort()

print (charList)		# ["a", "b", "c", "d"]

Happy Learning !!

Read More:

Python – Lists vs Tuples

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode