DEV Community

atchukolanaresh
atchukolanaresh

Posted on

Python Lists

Python Technical Paper

Lists:

Python lists are mutable(changeable), which means we can change their elements after they've been formed. Lists are one of four built-in python built - in Data structures storing data collections; the other three are Tuple, Set, and Dictionary, all of which have different properties and applications.

## Characteristics of a Python List:

  • Ordered: Lists maintain the order in which the data is inserted.
    • Mutable: In list element(s) are changeable.
    • Heterogenous: Lists can store elements of various data types.
    • Dynamic: List can expand or shrink automatically to accommodate the items accordingly
    • Duplicate Elements: Lists allow us to store duplicate data.

Note: Arrays are homogeneous and Lists are hetrogeneous. So Both are Different.

Creating Lists in Python:

A list is created by placing the items/ elements separated by a comma (,) between the square brackets ([ ]). Let’s see how we can create Lists in Python in different ways.

#Creation of a List in Python

# Creating an empty List
empty_List = []

# Creating a List of Integers
integer_List = [26, 12, 97, 8]

# Creating a List of floating point numbers
float_List = [5.8, 12.0, 9.7, 10.8]
# Creating a List of Strings
string_List = ["Interviewbit", "Preparation", "India"]

# Creating a List containing items of different data types
List = [1, "Interviewbit", 9.5, 'D']

# Creating a List containing duplicate items
duplicate_List = [1, 2, 1, 1, 3,3, 5, 8, 8]
Enter fullscreen mode Exit fullscreen mode

List Methods:

Syntax of append() Function in Python

Append function in python has the following syntax:

myList.append(element)
Enter fullscreen mode Exit fullscreen mode

Parameters of append() Function in Python

It accepts a single element which could be any Python object

  • integer, floating number, boolean, string, list, user-defined object etc.## Example of append() Function in Python

Here we will add elements like integers, floating numbers, and a string to a list.

list1 = ['programming', 5, 'Hello geeks']

list1.append(10)

list1.append('python')

list1.append(27.5)

# Updated list after adding new elements
print(list1)

Enter fullscreen mode Exit fullscreen mode

Output

['programming', 5, 'Hello geeks', 10, 'python', 27.5]
Enter fullscreen mode Exit fullscreen mode

Syntax of extend() in Python

The syntax of the extend() method in Python is:

list.extend(iterable)

Enter fullscreen mode Exit fullscreen mode

The list extend() method is written with the list to be extended and an iterable is passed to it.

Parameters of extend() in Python

The list extend() method has only one parameter, an iterable. The iterable can be a list, tuple (it is like an immutable list), string, set, or even a dictionary.

Return Values from extend()

The list extend() method doesn't return anything, it just modifies the given list.

list.extend()

list.append()

Extending a list using iterable

list1 = [1, 2, 3]

list2 = [4, 5, 6]

list1.extend(list2)

print(list1)

Output: [1, 2, 3, 4, 5, 6]

Appending element to a list

list1 = [1, 2, 3]

list2 = [4, 5, 6]

list1.append(list2)

print(list1)

Output: [1, 2, 3, [4, 5, 6]]

Syntax of insert() function in Python

insert() function simply takes two parameters index at which the element is to be inserted and the element which is to be inserted.

My_list.insert(index, element)

Enter fullscreen mode Exit fullscreen mode

Parameters of insert() function in Python

Below are the parameters of the insert function:

  • index: The index at which the element is inserted. This parameter is of number type.
  • element: It is the element that is to be inserted into the list. This parameter can be of any data type(string, number, object).

Return Value of insert() function in Python

insert() method just inserts the element in the list and updates the list and so does not return any value or we can say that insert() method returns None.

Example of insert() function in Python

Let's take a look at a basic example of how insert() function is used:

# original list
lis = ['Welcome', 'Mountblue']

# inserting a string to the list
lis.insert(1, 'to')

# printing the list
print('List:', lis)

Enter fullscreen mode Exit fullscreen mode

Output: We have simply added the string in the list:

List: ['Welcome', 'to', 'Mountblue']
Enter fullscreen mode Exit fullscreen mode

list.remove(x)

Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.

pop():

Overview

The pop() function is a pre-defined, inbuilt function in Python lists. It removes an element from the specified index. If no index is provided, then it removes the last element.

Syntax of Python List pop()

The syntax of pop() is as follows,

list_name.pop(index)

Enter fullscreen mode Exit fullscreen mode

The list_name is the List on which the pop function will operate.

Parameters of Python List pop()

It accepts a single parameter,

  • index (optional): The pop() function accepts only one parameter: the item's index to be popped out from the list. If the index is not mentioned, it removes the last item from the list.

Return Value of Python List pop()

The pop() function returns the item, which is present at the specified index and to be removed.

Example of Python List pop()

fruits = ["apple", "orange", "banana", "pineapple"]

print(fruits.pop()) # removes and prints the last element
print(fruits)

print(fruits.pop(0)) # removes and prints the item at 0 index
print(fruits)

Enter fullscreen mode Exit fullscreen mode

Output:

pineapple
['apple', 'orange', 'banana']
apple
['orange', 'banana']
Enter fullscreen mode Exit fullscreen mode

clear():

Overview

The clear() function in Python removes all elements from a list. The function does not take any parameters and does not return anything.

Syntax of clear() function in Python

list.clear()

Enter fullscreen mode Exit fullscreen mode

Parameters of clear() function in Python

The clear method in Python doesn’t take any parameters.

Return Type of clear() function in Python

The clear() function simply clears the given list. It does not return any particular value.

Example of clear() function in Python

Code:

# declaring a list
my_list = [{1, 2}, ('xyz'), ['3.66', '2.2']]

# clearing the list
my_list.clear()

print('The list after using the clear function:', my_list)

Enter fullscreen mode Exit fullscreen mode

Output:

The list after using the clear function: []

Enter fullscreen mode Exit fullscreen mode

Index():

Overview

The index() method in Python searches an element in the list and returns its position/index. If there are duplicate elements, then by default, index() returns the position of the first occurrence of the element we are searching for in the list.

Syntax for index() function in Python

The syntax of the list ndex() method in Python is:

list.index(element, start, end)

Enter fullscreen mode Exit fullscreen mode

Parameters for index() function in Python

The list index() method can take at most three arguments as discussed below:

  1. element: It specifies the element to be searched in the list. It is a mandatory parameter. Hence it must be provided in the index() method.
  2. start (optional): It is an optional parameter that specifies the starting index from which the element should be searched. The starting index provided must be present in the range of our list; otherwise, index() will throw a ValueError. By default, the index() method searches for any element from the 0�0t^h^ index.
  3. end (optional): It is an optional parameter that specifies the position up to which the element should be searched. The end index provided must be in the range of our list. Otherwise, a ValueError will be thrown by the index() method. If "end" is not provided, then by default, the element is searched till the end of the list.

Return Value for index() function in Python

Return Type: int

The index() method in Python returns the index of an element we have specified for it.

Exception of index() function in Python?

If the element is not present in the list, the index() method returns a ValueError Exception. We can handle this error using a try-catch block, as discussed in later examples.

Code:

ls = [1,2,5,7,5,3,2,1,5,6]
result = ls.index(5) #find the position of first occurrence of 5 
print(f"First occurence of 5 is at index = {result}")

Enter fullscreen mode Exit fullscreen mode

Output:

use Index in Python

count():

Syntax of count() Function in Python

Python Count() function has following syntax:

string.count(substring/character, start=, end=)

Enter fullscreen mode Exit fullscreen mode

Parameters of count() Fucntion in Python

Three parameters are accepted by the count() function of python while using strings:

  • substring/character: Which is to be searched in the string.
  • start (optional): The value which is stated as the start position. It is inclusive, which means substring/character at this position is also included in the count. If we leave this parameter empty, then start is considered as 0th position by default.
  • end (optional): The value stated as the end position. It is exclusive, which means substring/character at this position is excluded from the count. If we leave this parameter empty, then the end is considered the last index of the string by default.

Return Value of count() Fucntion in Python

Return Type: integer

It returns the number of occurrences of substring/character in a string.

Example of count() Fucntion in Python

Let's use count() function on strings to find the occurrence of any character.

string1 = 'Hello There'
occurrenceOfE = string1.count('e')

print('occurrence of e in string: ', occurenceOfE)

Enter fullscreen mode Exit fullscreen mode

Output

occurrence of e in string:  3

Enter fullscreen mode Exit fullscreen mode

Explanation

  • We created a string and stored it into a variable.
  • Then, we calculated the occurrence of the character 'e' in the string and stored it in the variable.
  • Finally, we printed that variable and got the occurrence of 'e' in the string.

sort():

The sort function can be used to sort the list in both ascending and descending order. It can be used to sort lists of integers, floating point numbers, strings, and others. Its time complexity is O(NlogN).

Python sort() Syntax

The syntax of the sort() function in Python is as follows.

Syntax: list_name.sort(key=…, reverse=…)

Parameters:
By default, Python sort() doesn’t require any extra parameters and sorts the list in ascending order. However, it has two optional parameters:

  • key: function that serves as a key for the sort comparison
  • reverse: If true, the list is sorted in descending order.

Return value: The sort() does not return anything but alters the original list according to the passed parameter.

code:

# List of Integers

numbers = [1, 3, 4, 2]

# Sorting list of Integers

numbers.sort(reverse=True)

print(numbers)

# List of Floating point numbers

decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68]

# Sorting list of Floating point numbers

decimalnumber.sort(reverse=True)

print(decimalnumber)

# List of strings

words = ["Geeks", "For", "Geeks"]

# Sorting list of strings

words.sort(reverse=True)

print(words)

copy():

Syntax of Copy in Python

The syntax of the copy() method in python is simple. The method is called on objects in the following way:

list.copy()

Enter fullscreen mode Exit fullscreen mode

Parameters of Copy in Python

The copy method in python provided in the standard library does not take any parameter as input.

Return Value of Copy in Python

Blockquote

The python copy method returns a shallow copy of the object it was called on. We will discuss shallow copy soon.

Example

Code:

my_list = [1, 2, 3]  # initializing a list 
copy_of_list = my_list.copy()  # using standard library copy() method to create shallow copy of list 
print(copy_of_list)

Enter fullscreen mode Exit fullscreen mode

Output:

[1, 2, 3]

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
vineetjadav73 profile image
vineetjadav

If you're serious about a career in data science and you're based in Delhi, look no further. This data science course in Delhi provides top-notch training and prepares you for success!