Skip to main content

Python List

What is a List?

List is a data type in Python.

List is used to store multiple values ( it can string, integer, float and other lists also ) in a single variable.

Lists are mutable, which means you can modify, add, and remove elements from them.

We can define a list in the following ways,

1. myList = [value1, value2, value3]

2. myTuple = (value1, value2, value3)

  • myTupleList = list(myTuple)

3. myStr = 'My String'

  • myStrList = list(myStr) 

Example:

a = [1,2,3]

print(a)

Output: [1,2,3]

You can access individual elements in a list using square brackets and the index of the element. Indexing starts from 0 in the Python List.

Like we want to access the third element of the above example list, we can write,

a[2]

Output: 3

If we want a string in a list, we will use double quotes for the element. Also if we want to use a list in the list we can use it.

Example:

myList = [2,4, ["a", 4]]

myList[2]

Output: ["a", 4]

List can have duplicate elements.

We can add, remove and alter the element in the list. Also we can join more than one list also copy, sorting elements. There are many list methods are available in python list concept.

I will give some of the methods here.

>> append():

myList = ["a", "b", "c"]

myList.append("d")

print(myList)

Output:["a", "b", "c", "d"]

>> count():

myList = ["a", "b", "c", "d, "b", "a"]

myList.count("b")

print(myList)

Output: 2

>> sort():

myList = ["India", "Canada", "Egypt"]

myList.sort()

print(myList)

Output:["Canada", "Egypt", "India"]

>> insert():

myList = ["a", "b", "c"]

myList.insert(2, "d")

print(myList)

Output:["a", "b", "d", "c"]

>> extend():

myListA = ["a", "b", "c"]

myListB = ["d","e"]

myListA.extend(myListB)

print(myListA)

Output:["a", "b", "c", "d", "e"]

>> copy():

myList = ["a", "b", "c"]

newMyList = myList.copy()

print(newMyList)

Output:["a", "b", "c"]

>> index():

myList = ["a", "b", "c"]

indexNo = myList.index("b")

print(indexNo)

Output:1

>> clear():

myList = ["a", "b", "c"]

myList.clear()

print(myList)

Output:[]

>> reverse():

myList = ["a", "b", "c"]

myList.reverse()

print(newMyList)

Output:["c", "b", "a"]

>> pop():

myList = ["a", "b", "c"]

myList.pop(1)

print(myList)

Output:["a", "c"]

>> remove():

myList = ["a", "b", "c"]

myList.remove("a")

print(myList)

Output:["b", "c"]

These are main list methods that are used widely in real time projects. This article will be helpful to you for the learning about list and its use in real world.




Comments