General

Python List

General May 17, 2019
Python List

Python List

Python lists are mutable sequences. They are very similar to tuples, but they don’t have the restrictions of immutability. Lists are commonly used to storing collections of homogeneous objects, but there is nothing preventing you from store heterogeneous collections as well. Lists can be created in many different ways.

Let’s see an example:

>>> []  # empty list
[]
>>> list()  # same as []
[]
>>> [1, 2, 3]  
[1, 2, 3]
>>> [x + 5 for x in [2, 3, 4]]  # Python is magic
[7, 8, 9]
>>> list((1, 3, 5, 7, 9))  # list from a tuple
[1, 3, 5, 7, 9]
>>> list('hello')  # list from a string
['h', 'e', 'l', 'l', 'o']

In the previous example, showed you how to create a list using different techniques. would like you to take a good look at the line that says Python is magic, which I am not expecting you to fully understand at this point.That is called a list comprehension, a very powerful functional feature of Python

Creating lists is good, but the real fun comes when we use them, so let’s see the main methods they gift us with:

Example:

>>> a = [1, 2, 1, 3]
>>> a.append(13)  # we can append anything at the end
>>> a
[1, 2, 1, 3, 13]
>>> a.count(1)  # how many `1` are there in the list?
2
>>> a.extend([5, 7])  # extend the list by another (or sequence)
>>> a
[1, 2, 1, 3, 13, 5, 7]
>>> a.index(13)  # position of `13` in the list (0-based indexing)
4
>>> a.insert(0, 17)  # insert `17` at position 0
>>> a
[17, 1, 2, 1, 3, 13, 5, 7]
>>> a.pop()  # pop (remove and return) last element
7
>>> a.pop(3)  # pop element at position 3
1
>>> a
[17, 1, 2, 3, 13, 5]
>>> a.remove(17)  # remove `17` from the list
>>> a
[1, 2, 3, 13, 5]
>>> a.reverse()  # reverse the order of the elements in the list
>>> a
[5, 13, 3, 2, 1]
>>> a.sort()  # sort the list
>>> a
[1, 2, 3, 5, 13]
>>> a.clear()  # remove all elements from the list
>>> a
[]

The preceding code gives you a roundup of a list’s main methods. I want to show you how powerful they are, using extend as an example.

You can extend lists using any sequence type:

>>> a = list('hello')  # makes a list from a string
>>> a
['h', 'e', 'l', 'l', 'o']
>>> a.append(100)  # append 100, heterogeneous type
>>> a
['h', 'e', 'l', 'l', 'o', 100]
>>> a.extend((1, 2, 3))  # extend using tuple
>>> a
['h', 'e', 'l', 'l', 'o', 100, 1, 2, 3]
>>> a.extend('...')  # extend using string
>>> a
['h', 'e', 'l', 'l', 'o', 100, 1, 2, 3, '.', '.', '.']

Now, let’s see what the most common operations are you can do with lists:

>>> a = [1, 3, 5, 7]
>>> min(a)  # minimum value in the list
1
>>> max(a)  # maximum value in the list
7
>>> sum(a)  # sum of all values in the list
16
>>> len(a)  # number of elements in the list
4
>>> b = [6, 7, 8]
>>> a + b  # `+` with list means concatenation
[1, 3, 5, 7, 6, 7, 8]
>>> a * 2  # `*` has also a special meaning
[1, 3, 5, 7, 1, 3, 5, 7]

The last two lines in the preceding code are quite interesting because they introduce us to a concept called operator overloading. In short, it means that operators such as +, -. *, %, and so on, may represent different operations according to the context they are used in. It doesn’t make any sense to sum two lists, right? Therefore, the + sign is used to concatenate them. Hence, the * sign is used to concatenate the list to itself according to the right operand.

Defining a list in Python

The list elements are enclosed within squared brackets and each element is separated by a comma. Below is an example of a list in Python. Here, the variable named movies_list holds three values which are of string data type.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia"]

Accessing a list element in Python

Each value can be accessed individually by referring to the variable name along with the appropriate index number which is enclosed within squared brackets. The index, 0, corresponds to the first element within the array; the index, 1, corresponds to the second value within the list and so forth.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia"]
print(movies_list[0])
print(movies_list[1])
print(movies_list[2])

Output

Amazing Spiderman
Harry Potter
Anaesthesia

Adding more elements to a list in Python

You can also add more items or elements of the same data type into the list using the append() method.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia"]
movies_list.append("Iron Man")
print(movies_list)

Output

['Amazing Spiderman', 'Harry Potter', 'Anaesthesia', 'Iron Man']        

Removing selected or all elements within a Python list

Likewise, you can also remove an item from a list by using pop() or remove(). By default, pop removes the last item in a list if no index has been referenced. However, you can also choose to remove a specific element by referring to the index corresponding to the item. In this example, index[0] corresponds to “Amazing Spiderman” which would be removed.

Using pop() method

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
movies_list.pop(0)
print(movies_list)

Output

 ["Harry Potter", "Anaesthesia", "Iron Man"]

Using remove() method

Similarly, you can use remove() to remove an item from the list. However, instead of referring to an index value, we key in the exact name of the element. It removes only the first occurrence of the value you specified. Also note that it is case sensitive.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
movies_list.remove("Harry Potter")
print(movies_list)

Output

["Amazing Spiderman", "Anaesthesia", "Iron Man"]

Once you remove an item in an array, the order of the index can also change. In the example above, movies_list[1] corresponds to “Harry Potter” before it is removed from the array. After removing it, movie_list[1] would now correspond to “Anaesthesia” as that is the order of the index.

Using clear() method

If you want to remove all the elements in a list, you can use the clear() method.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
print("Before clearing list: ", movies_list)
movies_list.clear()
print("After clearing list: ", movies_list)

Output

Before clearing list:  ['Amazing Spiderman', 'Harry Potter', 'Anaesthesia', 'Iron Man']                             
After clearing list:  []      

Looping through a list in Python

You can also loop through all the items in an array using the for in loop. You can change the “each” keyword to any other word in the example below. Here, “each” represent the individual item within a list and keeps looping through until the last item in the list.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
for each in movies_list:
    print(each)

Output

 Amazing Spiderman
 Harry Potter
 Anaesthesia
 Iron Man

Finding length of list in Python

You can find the length of the list by using the len() method. Length returns the total number of items in a list.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
print("There are ", len(movies_list), "items in this array")

Output

There are 4 items in this array

Sorting lists in Python

The items within a list can be sorted in alphabetical or numerical order by using the sort() method.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
score_list = [3, 6, 3, 1]
print(movies_list.sort())
print(movies_list)
print(score_list.sort())
print(score_list)

Output

['Amazing Spiderman', 'Anaesthesia', 'Harry Potter', 'Iron Man']  
[1, 3, 3, 6]     

Searching a list element in Python

The index() method can be used to find the position or index of an existing element within a list. Enter the name of the element inside the parenthesis to find its index. Note that it is case sensitive.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
print("Index value of Iron Man is ", movies_list.index("Iron Man"))

Output

Index value of Iron Man is  3

Copying a list in Python

A list can be duplicated by using the copy() method where you can copy the list to a new variable.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
movies_list2 = movies_list.copy()
print("Original list: ", movies_list)
print("New list: ", movies_list2)

Output

Original list:  ['Amazing Spiderman', 'Harry Potter', 'Anaesthesia', 'Iron Man']
New list:  ['Amazing Spiderman', 'Harry Potter', 'Anaesthesia', 'Iron Man']    

Click Here-> Get Python Training with Real-time Projects

Besant Technologies – Chennai & Bangalore Branch Locations

Besant Technologies - Velachery Branch

Plot No. 119, No.8, 11th Main road, Vijaya nagar,

Velachery, Chennai - 600 042

Tamil Nadu, India

Landmark - Reliance Digital Opposite Street

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Tambaram Branch

No.2A, 1st Floor, Duraisami Reddy Street,

West Tambaram, Chennai - 600 045

Tamil Nadu, India

Landmark - Near By Passport Seva

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - OMR Branch

No. 5/318, 2nd Floor, Sri Sowdeswari Nagar,

OMR, Okkiyam Thoraipakkam, Chennai - 600 097

Tamil Nadu, India

Landmark - Behind Okkiyampet Bus Stop,

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Porur Branch

No. 180/84, 1st Floor, Karnataka Bank Building,

Trunk Road, Porur, Chennai - 600 116

Tamil Nadu, India

Landmark - Opposite to Gopalakrishna Theatre

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Anna Nagar Branch

Plot No:1371, 28th street kambar colony,

I Block, Anna Nagar, Chennai - 600 040

Tamil Nadu, India

Landmark - Behind Reliance Fresh

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - T.Nagar Branch

Old No:146/2- New No: 48,

Habibullah Road,T.Nagar, Chennai - 600 017

Tamil Nadu, India

Landmark - Opposite to SGS Sabha

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Thiruvanmiyur Branch

22/67, 1st Floor, North mada street, Kamaraj Nagar

Thiruvanmiyur, Chennai 600041

Tamil Nadu, India

Landmark - Above Thiruvanmiyur ICICI Bank

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Siruseri Branch

No. 4/76, Ambedkar Street, OMR Road, Egatoor, Navallur,

Siruseri, Chennai 600130

Tamil Nadu, India

Landmark - Near Navallur Toll Gate, Next to Yamaha Showroom

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Maraimalai Nagar Branch

No.37, Ground Floor, Thiruvalluvar Salai,

Maraimalai Nagar,Chennai 603209

Tamil Nadu, India

Landmark - Near to Maraimalai Nagar Arch

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - BTM Layout Branch

No 2, Ground floor, 29th Main Road,

Kuvempu Nagar,BTM Layout 2nd Coming from Silkboard,

AXA company signal, Stage, Bangalore - 560 076

Karnataka, India

Landmark - Next to OI Play School

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Marathahalli Branch

No. 43/2, 2nd Floor, VMR Arcade,

Varthur Main Road, Silver Springs Layout,

Munnekollal, Marathahalli, Bengaluru - 560037

Karnataka, India

Landmark - Near Kundalahalli Gate Signal

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Rajaji Nagar Branch

No. 309/43, JRS Ecstasy, First Floor,

59th Cross, 3rd Block, Bashyam Circle,

Rajaji Nagar, Bangalore - 560 010

Karnataka, India

Landmark - Near Bashyam Circle

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Jaya Nagar Branch

No. 2nd Floor,1575,11th Main Road,

4th T-Block, Pattabhirama Nagar,

Jaya Nagar, Bangalore - 560 041

Karnataka, India

Landmark - Opposite to Shanthi Nursing Home

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Kalyan Nagar Branch

No.513, 4th Cross Rd

2nd Block, HRBR Layout,

Kalyan Nagar, Bangalore - 560 043

Karnataka, India

Landmark - Opposite to kalayan nagar Axis Bank

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Electronic City Branch

No. 7, 3rd Floor, Ganga Enclave,

Neeladri Road, Karuna Nagar, Doddathoguru Village,

Electronics City Phase 1, Electronic City,

Bangalore - 560100, karnataka, India

Landmark - Adjacent to HDFC Bank and State Bank Of India

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Indira Nagar Branch

No.54, 1st Floor,

5th Main kodihalli,

Bengaluru, Karnataka 560008, India

Landmark - Behind Leela Palace Hotel,

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - HSR Layout Branch

Plot No. 2799 & 2800, 27th Main,

1st Sector, HSR Layout,

Bengaluru, Karnataka 560102, India

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Hebbal Branch

No.29, 2nd Floor, SN Complex,

14th Main Road, E-Block Extention, Sahakara Nagar,

Bengaluru, Karnataka -560092, India

  +91-8767 260 270

  info@besanttechnologies.com

Scroll Up