Python List [With Examples]

Python list is used to hold the sequence of different types of data. Python lists are changeable, which means we can change their elements after they’ve been formed. However, Python has six data types that may be used to store sequences, but with the list being the most common and efficient.

Definition: A list may be described as a collection of different types of values or objects. The comma “,” separates the elements in the list, which are contained in square brackets [].

The following is an example of a list:

List1 = ["Ranjeet", 31, "Pakistan"]    
List2 = [1, 2, 3, 4, 5, 6]   

print(type(List1))  
print(type(List2))  

Output:

one

Creating a Python List

In Python, you may make a list by simply putting the sequence inside square brackets[]. A list, unlike Sets, does not require a built-in function to be created.

Example 01: Creating different lists

# Python program to demonstrate
# Creation of List
 
# Creating a List
List = []
print("Blank List: ")
print(List)
 
# Creating a List of numbers
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
 
# Creating a List of strings and accessing
# using index
List = ["Softhunt", "Ranjeet", ".net"]
print("\nList Items: ")
print(List[0])
print(List[2])
 
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Softhunt', 'Tutorials'] , ['Ranjeet']]
print("\nMulti-Dimensional List: ")
print(List)

Output:

two

Example 02: Creating a list with several elements that are distinct or duplicate

# Creating a List with
# the use of Numbers
# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)
 
# Creating a List with
# mixed type of values
# (Having numbers and strings)
List = [1, 2, 'Softhunt', 4, '.net', 6]
print("\nList with the use of Mixed Values: ")
print(List)

Output:

three

How to know size of Python list

In many cases, we want the size of the string or list so let’s have looked at the example which will show the size of the list.

Example 03:

# Creating a List
List1 = []
print(len(List1))
 
# Creating a List of mixed values
List2 = ["Softhunt", ".net", 14]
print(len(List2))

# Creating a List of numbers
List3 = [10, 20, 14, 31, 3]
print(len(List3))

Output:

four

How to add Elements to Python list

In this section, we will look at three different methods to add an element to the list.

  1. append() method
  2. insert() method
  3. extend() method

1) Using append() method

The built-in append() method may be used to add elements to the List. The append() function can only add one element to the list at a time; loops are needed to add many entries to the list with the append() method. Because tuples are unchangeable, they may also be added to the list using the append function. Lists, unlike Sets, may be appended to an existing list using the append() function.

Example 04:

# Python program to demonstrate
# Addition of elements in a List
 
# Creating a List
List = []
print("Initial blank List: ")
print(List)
 
# Addition of Elements
# in the List
List.append(7)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)
 
# Adding elements to the List
# using Iterator
for i in range(5, 10):
    List.append(i)
print("\nList after Addition of elements from 5-10: ")
print(List)
 
# Adding Tuples to the List
List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)
 
# Addition of List to a List
List2 = ['softhunt', '.net']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)

Output:

five

2) Using insert() method

The append() function only works for adding entries to the end of the List; the insert() method is used for adding elements to the appropriate location. Unlike append(), which just requires one parameter, insert() requires two arguments (position, value).

Example 05:

# Python program to demonstrate
# Addition of elements in a List
  
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
 
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(0, 0)
List.insert(5, 'Softhunt.net')
print("\nList after performing Insert Operation: ")
print(List)

Output:

Python list 5

3) Using extend() method

Apart from the append() and insert() methods, there is one additional technique for adding elements to a list: extend(). This function is used to add many entries to the end of the list at the same time.

Note: The methods append() and extend() can only add entries at the end of a list.

Example 06:

# Python program to demonstrate
# Addition of elements in a List
   
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
 
# Addition of multiple elements
# to the List at the end
# (using Extend Method)
List.extend([8, 'Softhunt', 'Tutorials'])
print("\nList after performing Extend Operation: ")
print(List)

Output:

seven

How to access Python list elements

  • The index number can be used to retrieve the list elements.
  • To get to a specific item in a list, use the index operator [].
  • An integer must be used as the index.
  • Nested indexing is used to retrieve nested listings.

Example 07: This example shows accessing multiple elements from the list.

# Python program to demonstrate
# accessing of element from list
 
# Creating a List with
# the use of multiple values
List = ["Softhunt", ".net", "Tutorials"]
 
# accessing a element from the
# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])
 
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Tutorials', 'Hello'] , ['Softhunt']]
 
# accessing an element from the
# Multi-Dimensional List using
# index number
print("\nAccessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])

Output:

eight

Example 08: This example shows Accessing element using negative indexing

List = [1, 2, 'Softhunt', 4, '.net', 6, 'Tutorials']
 
# accessing an element using
# negative indexing
print("Accessing element using negative indexing")
 
# print the last element of list
print(List[-1])
 
# print the third last element of list
print(List[-5])

Output:

Python list 4

How to Remove an element from a Python list

In this section, we will look at two different methods to remove an element from the list.

  1. Using remove() method
  2. Using pop() method

1) Using remove() method

The built-in remove() function can be used to remove elements from the List, however, if the element doesn’t exist in the set, an error will occur. The Remove() function only removes one element at a time; the iterator is used to remove a range of elements. The remove() method removes the specified item.

Note: In a List, the Remove method will only remove the first occurrence of the searched element.

Example 09:

# Python program to demonstrate
# Removal of elements in a List
 
# Creating a List
List = [1, 2, 3, 4, 5, 6,
        7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
 
# Removing elements from List
# using Remove() method
List.remove(3)
List.remove(8)
print("\nList after Removal of two elements: ")
print(List)
 
# Removing elements from List
# using iterator method
for i in range(1, 3):
    List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)

Output:

ten

2) Using pop() method

The pop() method can also be used to remove and return an element from a set, but it only removes the final element by default. To remove an element from a specified location in the List, supply the element’s index as an argument to the pop() method.

Example 10:

List = [1,2,3,4,5]
 
# Removing element from the
# Set using the pop() method
List.pop()
print("\nList after popping an element: ")
print(List)
 
# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(1)
print("\nList after popping a specific element: ")
print(List)

Output:

Python list 3

How to Slice list OR List Silicing

There are several ways to print the entire list with all of its elements in Python List, but we utilize the Slice operation to display a selected range of elements from the list.

  • The colon is used to conduct the slice operation on Lists “:”.
  • Use [: Index] to print elements from the beginning to the end of a range.
  • [:-Index] print elements from the end to the beginning.
  • [Index:] to print elements from a specific Index to the end.
  • [Start Index:End Index] print elements within a range.
  • [:] to print the entire List using the slicing operation.
  • Use [::-1] to print the whole List in reverse order.

Example 11: This example shows you different samples of slicing.

# Python program to demonstrate
# Removal of elements in a List
 
# Creating a List
List = ['S','O','F','T','H','U',
        'N','T','.','N','E','T']
print("Initial List: ")
print(List)
 
# Print elements of a range
# using Slice operation
Sliced_List = List[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_List)
 
# Print elements from a
# pre-defined point to end
Sliced_List = List[5:]
print("\nElements sliced from 5th "
      "element till the end: ")
print(Sliced_List)
 
# Printing elements from
# beginning till end
Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)

Output:

Python list 2

Note: Use Negative Indexes to print List entries from the rear-end.

Example 12: This example shows you negative list slicing.

# Creating a List
List = ['S','O','F','T','H','U',
        'N','T','.','N','E','T']
print("Initial List: ")
print(List)

# Print elements from beginning
# to a pre-defined point using Slice
Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last: ")
print(Sliced_List)
 
# Print elements of a range
# using negative index List slicing
Sliced_List = List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)
 
# Printing elements in reverse
# using Slice operation
Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)

Output:

Python list 1

List Comprehension

List comprehensions are used to generate new lists from iterables such as tuples, strings, arrays, and lists.

A list comprehension is made of brackets that hold the expression that is run for each element, as well as a for loop that iterates through each element.

Syntax:

newList = [ expression(element) for element in oldList if condition ]

Example 13:

# Python program to demonstrate list
# comprehension in Python
   
# below list contains square of all
# odd numbers from range 1 to 10
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print (odd_square)

Output:

Python list

The above code is identical to – for ease of comprehension.

Example 14: same as example 13

# for understanding, above generation is same as,
odd_square = []
 
for x in range(1, 11):
    if x % 2 == 1:
        odd_square.append(x**2)
 
print (odd_square)

Output:

fourteen

Python List Methods

FunctionDescription
Append()Add an element to the end of the list
Extend()Add all elements of a list to another list
Insert()Insert an item at the defined index
Remove()Removes an item from the list
Pop()Removes and returns an element at the given index
Clear()Removes all items from the list
Index()Returns the index of the first matched item
Count()Returns the count of the number of items passed as an argument
Sort()Sort items in a list in ascending order
Reverse()Reverse the order of items in the list
Copy()Returns a copy of the list

Built-in functions in Python with List

FunctionDescription
reduce()apply a function to all of the list items with its argument saves the intermediate result and only returns the final summation value
sum()Sums up the numbers in the list
ord()The Unicode code point of the specified Unicode character is returned as an integer.
cmp()If the first list is “greater” than the second list, this method returns 1.
max()return maximum element of a given list
min()return minimum element of a given list
all()Returns true if all element is true or if the list is empty
any()If any entry in the list is true, return true. Return false if the list is empty.
len()Returns length of the list or size of the list
enumerate()Returns enumerate object of the list
accumulate()apply a function to all of the list members with its parameter produces a list containing the intermediate results
filter()tests if each element of a list is true or not
map()after applying the supplied function on each item of a specified iterable, provide a list of the results
lambda()This function accepts any number of inputs but only evaluates and returns one expression.

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. Python Strings with Examples
  2. Arrays in Python
  3. Python Tuples

Leave a Comment