The sequence is the most basic data structure in Python.
A number is allocated to each element of a sequence - its position or index.
The initial index is zero, then one, two, three, and so on.
Python contains six built-in sequence types, but the most frequent are list and tuples, in this article we will discuss about python list in brief.
With all sequence kinds, there are several things you can do.
Indexing, slicing, adding, multiplying, and verifying for membership are some of these operations.
Python also includes built-in functions for determining the length of a sequence as well as its greatest and smallest members.
In Python, a list is used to store 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 can be used to store sequences, with the list being the most common and stable. A list can be defined as a collection of distinct types of values or items. The comma (,) separates the elements in the list, which are enclosed in square brackets [].
Example :List1 = ["Simran", 102, "India"]
List2 = [10, 12, 37, 14, 25, 62]
In Python, lists are ordered and have a count.
A list's elements are indexed in a specific order, with 0 serving as the first index.
Each element in the list has its own separate spot in the list, allowing duplication of elements in the list while maintaining the credibility of each member.
Note: Lists are a good way to keep track of a succession of data and iterate over it.
The following traits can be found on the list:
🚀 The lists are arranged in alphabetical order.
🚀 The list's element can be accessed by index.
🚀 The mutable type is represented by lists.
🚀 The types of the lists are mutable.
🚀 The amount of different elements can be stored in a 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.
The list, unlike Sets, can contain mutable elements.
# Creating an empty List List1 = [] print("Blank List: ") print(List1) # Creating a List of numbers List2 = [10, 120, 14] print("\nList of numbers: ") print(List2) # Creating a List of strings List3 = ["Hey", "Hello", "Mojos"] print("\nList Items: ") print(List3) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List4 = [['hey', 'hello'], ['Mojos']] print("\nMulti-Dimensional List: ") print(List4)
Blank List: [] List of numbers: [10, 120, 14] List Items: ["Hey", "Hello", "Mojos"] Multi-Dimensional List: [['hey', 'hello'], ['Mojos']]
Multiple distinct or duplicate values can be given as a sequence at the time of list construction since a list can contain duplicate items with distinct places.
Example :# Creating a List with duplicate numbers List1 = [10, 20, 40, 40, 30, 30, 30, 60, 50] print("\nList with duplicate Numbers: ") print(List1) # Creating a List of numbers List2 = [10, "Spin", 14.0] print("\nList of mixed values: ") print(List2)
List with duplicate Numbers: [10, 20, 40, 40, 30, 30, 30, 60, 50] List of mixed values: [10, "Spin", 14.0]
Using len() function we can get the size of the list.
Example :List1 = ["Simran", 102, "India"] print(len(List1)) List2 = [10, 12, 37, 14, 25, 62] print(len(List2))
3 6
There are several ways to print the entire List with all of its elements in Python List, but we utilise the Slice operation to print 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] to print elements from the end to the beginning, [Index:] to print elements from a specific Index to the end, [Start Index:End Index] to print elements within a range, and [:] to print the entire List using the slicing operation.
Use [::-1] to print the entire List in reverse order.
Use Negative Indexes to print List entries from the backend.
The indexing is handled in the same way as the strings are handled.
The slice operator [ can be used to access the list's elements.
The index starts at 0 and runs all the way to length -1.
The 0th index is used to store the initial element of the list, the 1st index is used to store the second element of the list, and so on.
Using the following syntax, we can get the list's sub-list.
list_name(start, stop, step)
🚀 The start indicates the start of the iteration.
🚀 The stop indicates that the loop will continue until it reaches stop-1. Iterations 1 to 4 will be generated by range(1,5). It's a choice.
🚀 The step size is used to skip the iteration's specific numbers. It's entirely up to you whether or not you want to use it. The step size is set at 1 by default. It's a choice.
# List slicing in Python list = [10, 20, 30, 40, 50, 60] # elements from index 2 to index 4 print(my_list[2:5]) # elements from index 3 to end print(my_list[3:]) # elements beginning to end print(my_list[:])
[30, 40, 50] [40, 50, 60] [10, 20, 30, 40, 50, 60]
Python, unlike other programming languages, allows you to employ negative indexing. From the right, the negative indices are counted. The index -1 is assigned to the list's last (rightmost) member; the index -2 is assigned to its adjacent left element, and so on until the list's left-most elements are met.
Example Code :# Creating a List List = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] 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)
Initial List: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] Elements sliced till 6th element from last: [10, 20, 30, 40, 50, 60, 70] Elements sliced from index -6 to -1 [50, 60, 70, 80, 90, 100] Printing List in reverse: [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
The built-in append() function can be used to add elements to the List. The append() method can only add one element to the list at a time; loops are needed to add many elements to the list with the append() method. Because tuples are immutable, they can also be added to the list using the append method. Lists, unlike Sets, can be appended to an existing list using the append() method.
# Creating a List List = [] print("Initial List: ") print(List) # Addition of Elements in the List List.append(10) List.append(20) List.append(40) print("\nList after Addition of elements: ") print(List) # Adding elements to the List using Iterator for i in range(1, 4): List.append(i*10) print("\nList after Addition of elements from 1-3: ") print(List) # Adding Tuples to the List List.append((50, 60)) print("\nList after Addition of a Tuple: ") print(List)
Initial List: [] List after Addition of elements: [10, 20, 40] List after Addition of elements from 1-3: [10, 20, 40, 10, 20, 30] List after Addition of a Tuple: [10, 20, 40, 10, 20, 30, (50, 60)]
The append() function only works for adding entries to the end of the List; the insert() method is used for adding elements to the desired location. Unlike append(), which just requires one argument, insert() requires two arguments (position, value).
# Creating a List List = [10,20,30,40] print("Initial List: ") print(List) # Addition of Element at # specific Position # (using Insert Method) List.insert(3, 120) List.insert(0, 'logicmojo') print("\nList after performing Insert Operation: ") print(List)
Initial List: [10,20,30,40] List after performing Insert Operation: ['logicmojo', 10, 20, 30, 120, 40]
Apart from the append() and insert() methods, there is one more 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. It's worth noting that the append() and extend() methods can only add elements at the end of a list.
# Creating a List List = [10,20,30,40] print("Initial List: ") print(List) # Addition of multiple elements # to the List at the end # (using Extend Method) List.extend([3, 120, 'logicmojo']) print("\nList after performing Extend Operation: ") print(List)
Initial List: [10,20,30,40] List after performing Extend Operation: [10, 20, 30, 40, 3, 120, 'logicmojo']
The built-in append() function can be used to add elements to the List. The append() method can only add one element to the list at a time; loops are needed to add many elements to the list with the append() method. Because tuples are immutable, they can also be added to the list using the append method. Lists, unlike Sets, can be appended to an existing list using the append() method.
# Creating a List List = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] print("Initial List: ") print(List) # Removing elements from List # using Remove() method List.remove(10) List.remove(30) List.remove(40) print("\nList after removing three elements: ") print(List) Removing elements from List # using iterator method for i in range(1, 4): List.remove(i) print("\nList after removing of elements from 1-3: ") print(List)
Initial List: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] List after removing three elements: [20, 50, 60, 70, 80, 90, 100] List after removing of elements from 1-3: [ 70, 80, 90, 100]
The pop() method can be used to remove and return an element from a list, but it only removes the last element by default. To remove an element from a specific place in the list, supply the index of the element as an argument to the pop() method.
# Creating a List List = [10,20,30,40] print("Initial List: ") print(List) # Addition of Element at # Removing element at a # specific location from the # Set using the pop() method List.pop(2) print("\nList after performing pop Operation: ") print(List)
Initial List: [10,20,30,40] List after performing pop Operation: [10, 30, 40]
List comprehensions are used to generate new lists from iterables such as tuples, strings, arrays, and lists.
A list comprehension is made up of brackets that hold the expression that is run for each element, as well as a for loop that iterates through each element.
newList = [ expression(element) for element in oldList if condition ]
# below list contains square of all
# even numbers from range 1 to 10
even_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print(even_square)
[4, 16, 36, 64, 100]
A nested loop is one that is contained within another loop.
For each iteration of the "outer loop," the "inner loop" will be run once.
You use a "nested loop" when you have a block of code that you want to run x number of times and then another block of code within that code that you want to execute y number of times.
These are frequently used in Python when dealing with a list of lists - an iterable object within an iterable object.
# Correcting mistake values in a list even = [2, 3, 5, 7, 11] # change the 1st item even[1] = 4 print(even) # change 2nd to 4th items odd[2:5] = [6, 8, 10] print(even)
[2, 4, 5, 7, 11] [2, 4, 6, 8, 10]
Python contains a plethora of helpful list functions that make working with lists a breeze. Here are a few of the most common list approaches.
🚀 Append():
Add a new element to the list's end.
🚀 Extend() : Adds all of a list's elements to another list.
🚀 Insert() : Adds a new item to the specified index.
🚀 Remove():
Adds a new item to the list.
🚀
Pop() : It is a function that removes and returns an element at the specified index.
🚀 Clear() : clears the list of all elements.
🚀 index() :The index of the first matched item is returned by index().
🚀
Count():
The number of objects supplied as an argument is counted and returned.
🚀
Sort():
In a list, sort the entries in ascending order.
🚀
Reverse():
In the list copy, reverse the order of the entries ()
🚀 copy():
A duplicate of the listd list methods is returned.
Let's overlook some built-in function in python list
🚀
reduce() : Applies a function to all of the list elements in its input, saves the intermediate result, and only returns the final summation value.
🚀 sum ():
Adds the numbers in the list together.
🚀 ord ():
Returns the Unicode code point of the specified Unicode character.
🚀 cmp():If the first list is "greater" than the second list, this method returns 1.
🚀
max():
return the list's maximum element.
🚀 min ():
return the smallest element in a provided.
🚀 all ():
Returns true if all of the elements in the list are 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 the length of the list or the size of the list.
🚀 enumerate ():
Returns an enumerate object of the list .
🚀 accumulate(): applies a specific function to all of the list elements and returns a list containing the intermediate results.
🚀 filter() :checks whether each element of a list is true or not.
🚀 map() : Returns a list of result After applying the supplied function on each item of a specified iterable
🚀 lambda():
This function accepts any number of inputs but only evaluates and returns one expression.
Crack your next tech interview with confidence!
In this article, we looked at Python list, creating lists, changing list elements, removing elements, and other list operations with the help of examples.