WHAT IS LIST IN PYTHON?

573 viewsPYTHONPython
0

WHAT IS LIST IN PYTHON?

Saraswat World Changed status to publish June 16, 2023
0
LIST DEFINITION-

A LIST is basically a data structure consisting of a collection of any datatype ordered, changeable, and indexed elements or items, created by enclosing elements in square brackets or by using List() constructor. List items allow duplicate values and its first item has index [0].

Properties of List items-

Orderedโ€“ List items have a defined order, and that order will not change. If we add new items to a list, the new items will be placed at the end of the list.

Changeable or Mutableโ€“ We can change, add, and remove items in a list.

Allow Duplicatesโ€“ Since lists are indexed, lists can have items with the same value.

Python code

thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)

Output

['apple', 'banana', 'cherry', 'apple', 'cherry']

Any Datatype-List items can be of any data type.

A list with strings, integers, and boolean values-

list1 = ["abc", 34, True, 40, "male"]
HOW TO CREATE A LIST IN PYTHON?

Creating a Listย by using square bracketsย []

Python Code

fruits = ["apple", "banana", "cherry"]
print(fruits)

Output

['apple', 'banana', 'cherry']

Creating a List by using the list() Constructor

Python Code

fruits = list(("apple", "banana", "cherry"))
print(fruits)

Output

['apple', 'banana', 'cherry']
HOW TO ACCESS ITEMS OF PYTHON LISTS?

List items are indexed and we can access them by referring to the index number. The first item of a list has an index 0. Negative indexing means start from the end as -1 refers to the last item, -2 refers to the second last item etc.

Python code

fruits = ["apple", "banana", "cherry"]
print(fruits[-1],fruits[0])

Output

cherry apple

Usingย Range of Indexes

We can access items of a list as a new list containing items accessed by specifying the start and end range as shown below

Python Code

fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[1:3])

This will return the items from position 1 to 3, first item is having position 0, and item in position 3 is not included

Output

['banana', 'cherry']

Usingย Range of Negative Indexes

To access the items from the end of the list we need to provide a negative range. The result will include items available at index value from the start of range value and one less than the end of range value.

This example returns the items from โ€œkiwiโ€ (-3) to, but not including โ€œmangoโ€ (-1)

Python Code

fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[-3:-1])

Output

['kiwi', 'melon']

Usingย inย keyword

Python Code

fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)

Output

True
HOW TO CHANGE THE ITEMS OF THE LIST IN PYTHON?

We can change the value of items by referring to their index number as shown below

Python Code

fruits = ["apple", "banana", "cherry"]
fruits[2] = "blackcurrant"
print(fruits)

It will change the third item value

Output

['apple', 'banana', 'blackcurrant']

Changing a Range of Item Values in Python Lists

We can change the value of items within a specific range, by defining a list with the new values and referring to the range of index numbers where we want to insert the new values.

Python code

fruits = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
fruits[1:3] = ["strawberry", "papaya"]
print(fruits)

It will change values in the list from, banana to strawberry and cherry to papaya.

Output

['apple', 'strawberry', 'papaya', 'orange', 'kiwi', 'mango']

If we insert more items than we replace, the new items will be inserted where we specified, and the remaining items will move accordingly:

Python code

fruits = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
fruits[1:2] = ["strawberry", "papaya"]
print(fruits)

Output

['apple', 'strawberry', 'papaya', 'cherry', 'orange', 'kiwi', 'mango']

If we insert less items than we replace, the new items will be inserted where we specified, and the remaining items will move accordingly as shown in below example

Python code

fruits = ["apple", "banana", "cherry"]
fruits[1:3] = ["mango"]
print(fruits)

Output

['apple', 'mango']
HOW TO ADD ITEMS TO THE LIST?

We can add items to the list by-

Using the insert() method inย Python List

The insert() method inserts an item at the specified index by

Python code

fruits = ["apple", "banana", "cherry"]
fruits.insert(2, "mango")
print(fruits)

Output

['apple', 'banana', 'mango', 'cherry']

Using the append() method in Python Lists

append()ย method add an item to the end of list as shown below

Python code

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)

Output

['apple', 'banana', 'cherry', 'orange']

Using the extend() method in Python Lists

The extend() method can add any iterable object (lists, tuples, sets, dictionaries, etc.).

The extend() method append elements from another list to the current list as shown below-

Python code

fruits1 = ["apple","banana","cherry"]
fruits2 = ["mango","pineapple","papaya"]
fruits1.extend(fruits2)
print(fruits1)

Output

['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
HOW TO REMOVE ITEMS FROM THE LIST?

Using the remove() method in Python Lists

The remove() method removes the specified item.

Python code to remove items from the list-

fruits = ["apple","banana","cherry"]
fruits.remove("banana")
print(fruits)

Output

['apple', 'cherry']

Using the pop() method in Python Lists

The pop() method removes the item at the specified index. If we do not specify the index, the pop() method removes the last item.

Python code to remove the item at the specified index from the Python list

fruits = ["apple","banana","cherry"]
fruits.pop(2)
print(fruits)

Output

['apple', 'banana']

Using the del keyword in Python Lists

Theย delย keyword also removes the item at the specified index:

Python code to remove the item at the specified index from the Python list

fruits = ["apple","banana","cherry"]
del fruits[0]
print(fruits)

Output

['banana', 'cherry']

Theย delย keyword can also be used to delete the list completely.

Python code to delete the list completely

fruits = ["apple", "banana", "cherry"]
del fruits

To check the deleted list print the list fruits, and the output will be an error message.

print(fruits) #output will be an error message

Using the clear() method in the Python Lists

The clear() method empties the List.

The list will not be deleted, only its content gets deleted. The output will be an empty list.

Python code to clear the content of the Python List

fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)

Output

[]
HOW TO USE A LOOP IN PYTHON LISTS?

Using for loop in the Python Lists

Python code to print each item one by one using the for loop in the Python list

fruits = ["apple", "banana", "cherry"]
for x in fruits:
 print(x)

Output

apple
banana
cherry

We can also loop through the list items by referring to their index number. The range() and len() methods are used in for loop. The len() method will return the no. of items available in the loop and the range() method will return the range over which iteration is applied, it starts from 0 and end at one less than the input argument. The range() method in the following example creates the iterable [0,1,2].

fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
 print(fruits[i])

Output

apple
banana
cherry

Using the while loop in the Python Lists

We will use the len() method to get the length of the list, then start at 0 and loop our way through the list items by referring to their indexes. We will increase the index by 1 after each iteration.

Python code to print each item one by one using the while loop in the Python list

fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
 print(fruits[i])
 i = i + 1

Output

apple
banana
cherry

Using List Comprehension in the Python Lists

List Comprehension is used to shorten the code for loops

fruits = ["apple", "banana", "cherry"]
[print(x) for x in fruits]

Output

apple
banana
cherry

We can create new list using List Comprehension

condition providedย if โ€œaโ€ in xย is optional.

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)

Output

['apple', 'banana', 'mango']
HOW TO SORT A PYTHON LIST?

Using the sort() method in Python List

Ascending Sort

The sort() method sorts the list alphanumerically, ascending, by default

fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort()
print(fruits)

Output

['banana', 'kiwi', 'mango', 'orange', 'pineapple']

Descendingย Sort

The sort() method sorts the list alphanumerically, descending, by using the keyword argumentย reverse = True

fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort(reverse = True)
print(fruits)

Output

['pineapple', 'orange', 'mango', 'kiwi', 'banana']

Customize Sortย Function

The sort() method sorts the list using customize function.

We can also customize our own function by using the keyword argument

key = function.

The function will return a number that will be used to sort the list (the lowest number first)

Python Code to Sort the list based on how close the number is to 40

def myfunc(n):
  return abs(n - 40)
fruits = [80, 40, 55, 42, 43]
fruits.sort(key = myfunc)
print(fruits)

Output

[40, 42, 43, 55, 80]

Case Insensitive Sort

The sort() method is case-sensitive by default, resulting in all capital letters being sorted before lowercase letters.

For the case-insensitive sort function, use inbuiltย str.lowerย as a key function

fruits = ["banana", "Orange", "Kiwi", "cherry"]
fruits.sort(key = str.lower)
print(fruits)

Output

['banana', 'cherry', 'Kiwi', 'Orange']
HOW TO REVERSE THE ORDER OF A PYTHON LIST?

The reverse() method reverses the current sorting order of the elements of the list.

Using the reverse() method in the Python Lists

fruits = ["banana", "Orange", "Kiwi", "cherry"]
fruits.reverse()
print(fruits)

Output

['cherry', 'Kiwi', 'Orange', 'banana']
HOW TO COPY A LIST IN THE PYTHON LISTS?

Using the copy() method in the Python Lists

copy() method is an inbuilt method in Python that can be used to copy the list as shown in the below example

fruits = ["apple", "banana", "cherry"]
mylist = fruits.copy()
print(mylist)

Output

['apple', 'banana', 'cherry']

Using the list() method in the Python Lists

List() method is a constructor for list object as shown above in this article, same can be also used to copy the list as shown in below example-

fruits = ["apple", "banana", "cherry"]
mylist = list(fruits)
print(mylist)

Output

['apple', 'banana', 'cherry']
HOW TO JOIN LISTS IN PYTHON?

Using the + operator to concatenate or join Python Lists

list1 = ["a", "b", "c", "d"]
list2 = [1, 2, 3, 4]
list3 = list1 + list2
print(list3)

Output

['a', 'b', 'c', 'd', 1, 2, 3, 4]

Using the append() method to concatenate or join Python Lists

list1 = ["a", "b", "c", "d"]
list2 = [1, 2, 3, 4]
for x in list2:
  list1.append(x)
print(list1)

Output

['a', 'b', 'c', 'd', 1, 2, 3, 4]

Using the extend() method to concatenate or join Python Lists

list1 = ["a", "b", "c", "d"]
list2 = [1, 2, 3, 4]
list1.extend(list2)
print(list1)

Output

['a', 'b', 'c', 'd', 1, 2, 3, 4]
LIST OF IN-BUILT LIST METHODS IN THE PYTHON LISTS

Summary of List Methods, most of the methods are explained above in this article

Sr. No. Method Description-Code-Output
1 append() #Adds an element at the end of the list
fruits = [โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜cherryโ€™]
fruits.append(โ€œorangeโ€)
print(fruits)
#Output-[โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜cherryโ€™, โ€˜orangeโ€™]
2 clear() #Removes all the elements from the list
fruits = [โ€œappleโ€, โ€œbananaโ€, โ€œcherryโ€]
fruits.clear()
print(fruits)
#output- [ ]
3 copy() #Returns a copy of the list
fruits = [โ€œappleโ€, โ€œbananaโ€, โ€œcherryโ€]
mylist = fruits.copy()
print(mylist)
#output-[โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜cherryโ€™]
4 count() #Returns the number of elements with the specified value
fruits = [โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜cherryโ€™]
x = fruits.count(โ€œcherryโ€)
print(x)
#output- 1
5 extend() #Add the elements of a list (or iterable), to the end of the current list
list1 = [โ€œaโ€, โ€œbโ€, โ€œcโ€, โ€œdโ€]
list2 = [1, 2, 3, 4]
list1.extend(list2)
print(list1)
#output-[โ€˜aโ€™, โ€˜bโ€™, โ€˜cโ€™, โ€˜dโ€™, 1, 2, 3, 4]
6 index() #Returns the index of the first element with the specified value
fruits = [โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜cherryโ€™]
x = fruits.index(โ€œcherryโ€)
print(fruits)
#output- 2
7 insert() #Adds an element at the specified position
fruits = [โ€œappleโ€, โ€œbananaโ€, โ€œcherryโ€]
fruits.insert(2, โ€œmangoโ€)
print(fruits)
#output-[โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜mangoโ€™, โ€˜cherryโ€™]
8 pop() #Removes the element at the specified position
fruits = [โ€œappleโ€,โ€bananaโ€,โ€cherryโ€]
fruits.pop(2)
print(fruits)
#output- [โ€˜appleโ€™, โ€˜bananaโ€™]
9 remove() #Removes the item with the specified value
fruits = [โ€œappleโ€,โ€bananaโ€,โ€cherryโ€]
fruits.remove(โ€œbananaโ€)
print(fruits)
#output-[โ€˜appleโ€™, โ€˜cherryโ€™]
10 reverse() #Reverses the order of the list
fruits = [โ€œbananaโ€, โ€œOrangeโ€, โ€œKiwiโ€, โ€œcherryโ€]
fruits.reverse()
print(fruits)
#output-[โ€˜cherryโ€™, โ€˜Kiwiโ€™, โ€˜Orangeโ€™, โ€˜bananaโ€™]
11 sort() #Sorts the list
#syntax- list.sort(reverse=True|False, key=myFunc)
fruits = [โ€œorangeโ€, โ€œmangoโ€, โ€œkiwiโ€, โ€œpineappleโ€, โ€œbananaโ€]
fruits.sort() #sort in desc. order add argument reverse=True
print(fruits)
#output- [โ€˜bananaโ€™, โ€˜kiwiโ€™, โ€˜mangoโ€™, โ€˜orangeโ€™, โ€˜pineappleโ€™]
Python Lists Methods

 

Saraswat World Changed status to publish June 16, 2023
You are viewing 1 out of 1 answers, click here to view all answers.
Write your answer.

Posted

in

Tags:

Comments

Leave a Reply

A Tribute to Dilip Kumar