# All About Python List


## What is a List?
_In python list is a collection of items in a particular order. lists are like a container where we can store multiple values of any type. For creating a list in Python we use `[]` - square brackets, opening square brackets indicate the start of a list, and closing square brackets indicate the end of a list. We can store values of any type in a list, values of a list are known as elements and each element is separated by `,`. This is how a simple python list looks like  `['apple', 'grapes', 'banana', 'orange', 'guava']`. Unlike `string` or `tuple` lists are mutable which means we can modify a list. Here are a few examples of valid lists in python._
```python
# this is how we create a new list in python
list1 = [] # this is an empty list
# this is another way to create a new list in python
list1 = list() # this is an empty list
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava'] # list of strings
even_numbers = [2,4,6,8,10] #list of numbers
vowels = ['a','e','i','o','u'] #list of characters
list2 = ['hello', "2", 76, 8.23] #list of mixed values
list3 = ["How are You", ["hi", 4.5, 9], 98] #list of mixed values
```
## Accessing Element of a list.
_Lists are ordered collections of elements, each and every element in a list has its own index and we can use this index to access and modify elements of the list. Indexing starts from 0 and goes up to a length of the list -1. Here is a quick diagram of how indexing works. _


![Untitled presentation (1).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1667015668901/hIRCcwvMN.png align="left")
  ### Accessing Individual Elements of a list
To access an element of a list we write the name of the list followed by the index of the elements enclosed in square brackets. This is also known as indexing.

```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
# using forward indexing
fruits[0] #o/p ->'apple'
fruits[1] #o/p ->'grapes'
fruits[2] #o/p ->'banana'
fruits[3] #o/p ->'orange'
fruits[4] #o/p ->'guava'
# using backward indexing
fruits[-1] #o/p ->'guava'
fruits[-2] #o/p ->'orange'
fruits[-3] #o/p ->'banana'
fruits[-4] #o/p ->'grapes'
fruits[-5] #o/p ->'apple'

# using the element of a list in a simple sentence
message = "I like " + fruits[0] + " more than " + fruits[3]
print(message) # -> I like apple more than orange
```

  ### Accessing a range of Elements from a list(list slicing).
When we want to access a range of elements from a list we use list slicing, and we use list slicing when we have to work with a specific part of the list. For using list slicing we use a similar syntax to list indexing, instead of passing the index only we pass three parameters inside the square brackets `list_name[start_index:stop_index:step_value]`, step_value is optional and the default value for step_value is 1. one more thing to keep in mind is that `stop_index` is exclusive. Here are a few examples of list slicing.
```python
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

# it returns a new list with elements from index 10 to index 19, we don't get an element at index 20 because the stop_index is exclusive
alphabets[10:20] #o/p -> ['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't']

# when we pass the step_value of 2, we get a new list of every second element from index 10  to index 19.
alphabets[10:20:2]  #o/p -> ['k', 'm', 'o', 'q', 's']

# this will return a new list of the first 10 elements starting from index 0
alphabets[:10] # o/p -> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

# this will return a new list of elements starting at index 10 till the end of the list
  alphabets[10:]  # o/p -> ['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

# this will return a new list with every second element
alphabets[::2] # o/p -> ['a', 'c', 'e', 'g', 'i', 'k', 'm', 'o', 'q', 's', 'u', 'w', 'y']

# this will return a copy of the complete list
alphabets[:] # o/p -> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
```

## Modifying Element of a list
modifying a list is very similar to accessing a list, we use list indexing and list slicing to modify a list. Here are a few examples of modifying a list.

```python
# modifying a single element 
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']

fruits[1] = "mango" # this will change the element at index 1 to mango
print(fruits) #o/p ['apple', 'mango', 'banana', 'orange', 'guava']

# modifying multiple elements at a time
fruits[0:3] = ['Coconut', 'Pear', 'Dates'] # this will change elements at index 0,1and 2 to Coconut, Pear, Dates
print(fruits)
```
## Using the Membership operator with a list
we can use `in` and `not in` operators with a list, we use `in` and `not in` operators to check if the element is present in the list or not.
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
'apple' in fruits
# o/p ->True because apple is present in the list
'mango' in fruits
#o/p ->False because mango is not present in the list
'apple' not in fruits
#o/p -> False because apple is present in the list
'mango' not in fruits
#o/p -> True because mango is not present in the list
```
## Using a Comparison operator with a list
we can use a comparison operator like `<,>,==,!=` to compare two lists in python. When we compare two lists using the comparison operator, python compares each and every element of a list in lexicographical order.
```python
list1 = [10,20,30,40,50,60]
list2 = [10,20,30,40,50,60]
print(list1 == list2) #o/p -> True because each and every element of the list are same

list1 = [10,20,30,40,50,60]
list2 = [10,20,70,40,50,60]
print(list1 == list2) #o/p -> False because each and every element of the list are not same

list1 = [10,20,30,40,50,60]
list2 = [10,20,70,40,50,60]
print(list1 != list2) #o/p -> True

list1 = [10,20,30,40,50,60]
list2 = [10,20,70,40,50,60]
print(list1 < list2) #o/p -> True because third element of list1 is less than third element of list2

list1 = [10,20,30,40,50,60]
list2 = [10,20,70,40,50,60]
print(list1 > list2) #o/p -> False
``` 

## using `+` and `*` with the Python list
we can use the concatenation operator and replication operator with the python list. Here are a few examples.
```python
list1 = [10,20,30,40,50,60]
list2 = [70,80,90,100]
print(list1 + list2) #o/p -> [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

list1 = [10,20,30,40,50,60]
print(list1 *2) #o/p -> [10, 20, 30, 40, 50, 60, 10, 20, 30, 40, 50, 60]

```
## Length of a list
In python, we use the `len()` function to find the length of a list.  `len()` function tells us the number of elements in a list. This is how we use the `len()` function to find the length of a list.

```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
print(len(fruits)) # o/p -> 5 

list1 = [10,20,30,40,50,60]
list_length = len(list1)
print(list_length) # o/p -> 6 
```


## Traversing a list.
Traversing a list means processing each and every element of a list. We use a loop to traverse a list. 
```python
#syntax
for variable_name in your_list:
  #do something
#In each iteration value from your list will be assigned to variable_name and you can process that value in the way you want.

```
Example:-
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']

for fruit in fruits:
  print(fruit) # in each iteration fruit variable will be assigned a new value from the fruits list and I am printing that value.
  
#output
apple
grapes
banana
orange
guava
```
If we want to use the index of the elements to access them, then we can use the `range()` and the `len()` functions. 
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']

#syntax
# for variable_name in range(len(your_list)):
#   #do something
#   your_list[variable_name]

for index in range(len(fruits)):
  print(index)  # in each iteration index variable will be assigned the index of the elements from the fruits variable.

#output
0
1
2
3
4

for index in range(len(fruits)):
  print(fruits[index])  # this line prints the values from the fruits list from the passed index. this is the same as using the index to access individual elements from a list.

#output
apple
grapes
banana
orange
guava

```
## Python List Methods
Python comes with some built-in methods and functions. In this part of the article, we are going to learn about built-in methods of lists.

### list.append(element)
append method add a new element at the end of the list.
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
fruits.append('pear')
print(fruits) # o/p -> ['apple', 'grapes', 'banana', 'orange', 'guava', 'pear']
```
### list.extend(iterable)
extend method extends the list by adding all the elements from the iterable to the list.
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
another_fruits_list = ['pear','kiwi','coconut']
fruits.extend(another_fruits_list)
print(fruits) 
# o/p -> ['apple', 'grapes', 'banana', 'orange', 'guava', 'pear', 'kiwi', 'coconut']

fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
another_fruits_tuple = ('pear','kiwi','coconut')
fruits.extend(another_fruits_tuple)
print(fruits) 
# o/p -> ['apple', 'grapes', 'banana', 'orange', 'guava', 'pear', 'kiwi', 'coconut']
```
### list.insert(index,element)
insert method takes two arguments, the first one is `index` and the second one is `element`. We use the insert method when we want to add a new element at a specific index in a list. insert method add the element at the given index and shift the other element to the right by one position.
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
fruits.insert(1,'pear') # i want to add pear at index 1
print(fruits) 
# o/p -> ['apple', 'pear', 'grapes', 'banana', 'orange', 'guava']
```
### list.pop(index) / list.pop() 

the pop method is used to remove elements from the list, the pop method takes the index as an optional argument if we use `list.pop(index_of_item_you_want_to_remove)` then it removes the element from the list at the given index and returns it and if we use `list.pop()` then it removes the last element of the list and returns it. the pop method returns the removed element, so you can use the removed element later.

```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
fruits.pop() # if no index is passed it removes the last element
print(fruits) 
#o/-> ['apple', 'grapes', 'banana', 'orange']

fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
popped_element = fruits.pop() # it returns the popped element, so we can store the popped element in a variable and use that later.
print(popped_element) 
#o/p -> guava
print(fruits)
# o/p -> ['apple', 'grapes', 'banana', 'orange']

fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
fruits.pop(1) # removes the element at index 1
print(fruits)
```
### list.remove(element)

remove method is also used to remove elements from the list, but it takes an element as an argument and removes the element from the list and if there is a duplicate element in the list then it removes the first occurring element.
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
fruits.remove('grapes') 
print(fruits) 
#o/p-> ['apple', 'banana', 'orange', 'guava']

fruits = ['apple', 'grapes', 'banana', 'orange', 'guava', 'grapes'] 
fruits.remove('grapes') # grapes wat at two positions 1 and 5, 1 comes first so grapes at index 1 is removed
print(fruits) 
#o/p-> ['apple', 'banana', 'orange', 'guava', 'grapes']
```
### list.clear()
the `list.clear()` method removes all the elements from the list.
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
fruits.clear()
print(fruits) 
#o/-> []
```
### list.count(element)
`list.count()` method takes an element as an argument and returns the number of times the element occurs in the list.
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
element_count = fruits.count('grapes')
print(element_count)
#o/-> 1

fruits = ['apple', 'grapes', 'banana', 'orange', 'guava','grapes']
element_count = fruits.count('grapes')
print(element_count)
#o/-> 2

```
### list.sort()
This method is used to sort the list, by default this method sort the list in ascending order.
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava','grapes']
fruits.sort()
print(fruits)
#o/-> ['apple', 'banana', 'grapes', 'grapes', 'guava', 'orange']
```
### list.reverse()
This method is used to reverse the list. 
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']
fruits.reverse()
print(fruits)
#o/-> ['guava', 'orange', 'banana', 'grapes', 'apple']
```
### list.copy()
`list.copy()` method returns a copy of the original list. modifying the new list doesn't modify the original list.
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava',]
copied_list = fruits.copy()
print(copied_list)
#o/-> ['apple', 'grapes', 'banana', 'orange', 'guava']
```
### list.index(element)
`list.index()` method returns the index of the specified element if there is a duplicate element it returns the index of the first occurring element. It also takes two positional arguments `list.index(element,start_index,stop_index)`, and returns the index of the element between start_index and stop_index.
```python
fruits = ['apple', 'grapes', 'banana', 'orange', 'guava',]
index = fruits.index('grapes')
print(index)
#o/-> 1

fruits = ['apple', 'grapes', 'banana', 'orange', 'guava','grapes']
index = fruits.index('grapes')
print(index)
#o/-> 1


fruits = ['apple', 'grapes', 'banana', 'orange', 'guava','grapes']
index = fruits.index('grapes',2,6)
print(index)
#o/-> 5

```

## Conclusion
That's it for this article, Write your feedback in the comment section.


