Lists in Python

Learn how to create, access, modify, and work with lists in Python through clear examples and beginner-friendly explanations.

Loading...
Lists in Python

A list in Python is used to store multiple items in a single variable. These items are kept in a specific order, and you can change them anytime (that’s called being mutable).

Creating Lists

Lists are created using square brackets [], with items separated by commas.

A list can contain items of different data types.

For example:

# List of integers
list1 = [1,2,36,3,15]
 
# List of strings
list2 = ["Red", "Yellow", "Blue"]
 
# List of mixed data types
list3 = [1, "John",12, 5.3]
 
print(list1) # Output: [1, 2, 36, 3, 15]
print(list2) # Output: ['Red', 'Yellow', 'Blue']
print(list3) # Output: [1, 'John', 12, 5.3]

Length of List

You can find length of list (number of items in a list) using len() function.

For example:

list1 = [1,2,36,3,15] # This list has 5 numbers
lengthOfList = len(list1) # len() counts how many items are in the list
 
print(lengthOfList) # Output: 5

Accessing List Items

Each item in a list has a number called its index. Python starts counting from 0, so the first item is at index 0, the second at 1, and so on.

For example:

fruits = ["Orange", "Apple", "Banana"]
 
# Indexes:      0        1        2
 
 
print(fruits[0]) # Output: Orange
print(fruits[1]) # Output: Apple
print(fruits[2]) # Output: Banana

You can also access elements from the end of the list (-1 for the last element, -2 for the second-to-last element, and so on), this is called negative indexing.

For example:

fruits = ["Orange", "Apple", "Banana"]
 
# Negative:    -3       -2       -1
 
print(fruits[-1]) # Output: Banana 
print(fruits[-2]) # Output: Apple
print(fruits[-3]) # Output: Orange
 
# for understanding, you can consider this as fruits[len(fruits)-3]

Check if an item exists in the list

You can check whether an item is present in the list or not, using the in keyword.

Example 1:

fruits = ["Orange", "Apple", "Banana"]
if "Orange" in fruits:
    print("Orange is in the list.")
else:
    print("Orange is not in the list.")
 
# Output: Orange is in the list.

Example 2:

numbers = [1, 57, 13]
if 7 in numbers:
    print("7 is in the list.")
else:
    print("7 is not in the list.")
 
# Output: 7 is not in the list.

Slicing Lists

You can access a range of list items by giving start, end and jump(skip) parameters.

Slicing is like cutting a portion of a list. You tell Python where to start and stop, and it gives you that part.

Syntax:

listName[start : end : jumpIndex]

Note: jump Index is optional.

Example 1:

# Printing elements within a particular range
numbers = [1, 57, 13, 6, 18, 54]
 
# using positive indexes (this will print the items starting from index 2 and ending at index 4 i.e. (n-1))
print(numbers[2:5])	# Output: [13, 6, 18]
 
# using negative indexes (this will print the items starting from index -5 and ending at index -3 i.e. (-2-1))
print(numbers[-5:-2])	# Output: [57, 13, 6]

Example 2:

When no end index is provided, the interpreter prints all the values till the end.

# Printing all elements from a given index till the end
numbers = [1, 57, 13, 6, 18, 54]
 
# using positive indexes
print(numbers[2:])	# Output: [13, 6, 18, 54]
 
# using negative indexes
print(numbers[-5:])	# Output: [57, 13, 6, 18, 54]

Example 3:

When no start index is provided, the interpreter prints all the values from start up to the end index provided.

# Printing all elements from start to a given index
numbers = [1, 57, 13, 6, 18, 54]
 
# using positive indexes
print(numbers[:4])	# Output: [1, 57, 13, 6]
 
# using negative indexes
print(numbers[:-2])	# Output: [1, 57, 13, 6]

Example 4:

You can print alternate values by giving jump index.

# Printing alternate values
numbers = [1, 57, 13, 6, 18, 54]
 
#using positive indexes (here start and end indexes are not given and 2 is jump index.)
print(numbers[::2])	# Output: [1, 13, 18]
 
#using negative indexes (here start index is -2, end index is not given and 2 is jump index.)
print(numbers[-2::2])	# Output: [18]

List Comprehension

You can create new lists from other iterables like lists, tuples, dictionaries, sets, using list comprehensions.

Syntax:

List = [Expression(item) for item in Iterable if Condition]

Here,

  • Expression: It’s the item which is being iterated.
  • Iterable: It can be list, tuples, dictionaries, sets, etc.
  • Condition: Condition checks if the item should be added to the new list or not.

Example 1:

names = ["John", "Mark", "Bruno", "Dany"]
 
# This creates a new list of names that contain the letter "a"
# It goes through each item in the 'names' list and checks the condition
 
namesWith_a = [item for item in names if "a" in item]
 
print(namesWith_a) # Output: ['Mark', 'Dany']

Example 2:

names = ["John", "Mark", "Bruno", "Dany", "Jay"]
 
# Print list of names in which length of name is less than 4.
 
nameLength = [item for item in names if (len(item) < 4)]
print(nameLength) # Output: ['Jay']

List Methods

Python provides following methods to manipulate lists.

list.sort()

This method sorts the list in ascending order or alphabetically. The original list is updated.

Example 1:

fruits = ["banana", "apple", "orange", "plum"]
fruits.sort() # Strings are arranged in alphabetical (A-Z) order
print(fruits)
 
numbers = [14,2,7,3,2,1,8,1,10,18,5,3]
numbers.sort() # Numbers are arranged from smallest to largest.
print(numbers)

Output:

['apple', 'banana', 'orange', 'plum']
[1, 1, 2, 2, 3, 3, 5, 7, 8, 10, 14, 18]

To print the list in descending order, you have to give reverse=True as a parameter in the sort method.

For example:

fruits = ["banana", "apple", "orange", "plum"]
fruits.sort(reverse=True) # reverse=True sort items from Z to A
print(fruits)
 
numbers = [14,2,7,3,2,1,8,1,10,18,5,3]
numbers.sort(reverse=True) # reverse=True sort numbers from largest to smallest
print(numbers)

Output:

['plum', 'orange', 'banana', 'apple']
[18, 14, 10, 8, 7, 5, 3, 3, 2, 2, 1, 1]

The reverse parameter is set to False by default.

Note: Do not mistake the reverse parameter with the reverse method.

reverse()

This method reverses the order of the list.

Example:

fruits = ["banana", "apple", "orange", "plum"]
fruits.reverse() # Just flips the list, does not sort.
print(fruits)
 
numbers = [14,2,7,3,2,1,8,1,10,18,5,3]
numbers.reverse() # Reverses the list in its current order
print(numbers)

Output:

['plum', 'orange', 'apple', 'banana']
[3, 5, 18, 10, 1, 8, 1, 2, 3, 7, 2, 14]

index()

This method returns the index of the first occurrence of a specified value.

Example:

fruits = ["banana", "apple", "orange", "plum"]
print(fruits.index("orange")) # Finds the first position of "orange" in the list. Indexing starts from 0, so orange is at index 2.
# Output: 2
 
numbers = [14,2,7,3,2,1,8,1,10,18,5,3]
print(numbers.index(8)) # Finds the first position of 8 in the list. Indexing starts from 0, so 8 is at index 6.
# Output: 6

count()

This method returns the number of occurrences of a specified value.

Example:

fruits = ["banana", "apple", "orange", "plum", "orange"]
print(fruits.count("orange")) # Counts how many times "orange" appears in the list.
# Output: 2
 
numbers = [14,2,7,3,2,1,8,1,10,18,5,3]
print(numbers.count(2)) # Counts how many times 2 appears in the list.
# Output: 2

copy()

This method returns the copy of the list. This does not modify the original list.

Example:

fruits = ["banana", "apple", "orange", "plum", "orange"]
copiedList = fruits.copy() # Makes a new list that’s the same as fruits, but stored separately. Changing one won't affect the other.
 
print(fruits)
print(copiedList)

Output:

['banana', 'apple', 'orange', 'plum', 'orange']
['banana', 'apple', 'orange', 'plum', 'orange']

append()

This method appends items to the end of the existing list.

Example:

fruits = ["banana", "apple", "orange", "plum", "orange"]
fruits.append("grapes") # Adds "grapes" at the end of the list.
print(fruits)

Output:

['banana', 'apple', 'orange', 'plum', 'orange', 'grapes']

insert()

This method inserts an item at the given index. You have to specify index and the item to be inserted within the insert() method.

Example:

fruits = ["banana", "apple", "orange", "plum", "orange"]
fruits.insert(3, "grapes") # Inserts "grapes" at index 3. All items from index 3 onwards are pushed one step right.
 
print(fruits)

Output:

['banana', 'apple', 'orange', 'grapes', 'plum', 'orange']

extend()

This method adds an entire list or any other collection datatype (set, tuple, dictionary) to the existing list.

Example:

fruits = ["banana", "apple", "orange", "plum", "orange"]
vegetables = ["potato", "tomato", "spinach"]
fruits.extend(vegetables) # Adds all items from vegetables to the end of fruits. The original vegetables list is not modified.
 
print(fruits)

Output:

['banana', 'apple', 'orange', 'plum', 'orange', 'potato', 'tomato', 'spinach']

Concatenating Two Lists

You can combine two or more lists using the + operator.

Example:

fruits = ["banana", "apple", "orange", "plum", "orange"]
vegetables = ["potato", "tomato", "spinach"]
print(fruits + vegetables) # Combines two lists into a new one. Does not modify the original lists.

Output:

['banana', 'apple', 'orange', 'plum', 'orange', 'potato', 'tomato', 'spinach']

Support my work!