Python Lists
Published: 2023-05-11 06:55:29

# 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]
```

##  List Methods:

## Syntax of  append()  Function in Python

Append function in python has the following syntax:

```
myList.append(element)
```
## 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)

```

**Output**

```
['programming', 5, 'Hello geeks', 10, 'python', 27.5]
```
## Syntax of extend() in Python

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

```
list.extend(iterable)

```

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.

```python
My_list.insert(index, element)

```

## 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:

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

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

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

```

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

```python
List: ['Welcome', 'to', 'Mountblue']
```
## list.remove(_x_)

Remove the first item from the list whose value is equal to  _x_. It raises a  [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "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,

```python
list_name.pop(index)

```

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()

```python
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)

```

**Output:**

```plaintext
pineapple
['apple', 'orange', 'banana']
apple
['orange', 'banana']
```

## clear():

## Overview

The  clear()  function in  [Python](https://www.scaler.com/topics/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

```python
list.clear()

```

## 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:**

```python
# 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)

```

**Output:**

```python
The list after using the clear function: []

```

##  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](https://www.scaler.com/topics/python-list-index-method/)  in Python is:

```python
list.index(element, start, end)

```

## 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:**

```python
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}")

```

**Output:**

![use Index in Python](https://scaler.com/topics/images/use-index-in-python.webp)

## count():
## Syntax of  count()  Function in Python

Python  Count()  function has following syntax:

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

```

## 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.

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

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

```

**Output**

```python
occurrence of e in string:  3

```

**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](https://www.geeksforgeeks.org/python-programming-language/)  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:

```python
list.copy()

```

## 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:**

```python
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)

```

**Output:**

```python
[1, 2, 3]

```