What is pip LEARNOVITA

What is list in Python ? All you need to know [ OverView ]

Last updated on 28th Jan 2023, Artciles, Blog

About author

Nirvi (Python developer )

Nirvi is a Python developer with 7+ years of experience in the Hadoop ecosystem, including Sqoop, Hive, Spark, Scala, HBase, MapReduce, and NoSQL databases, such as HBase, Cassandra, and MongoDB. She spends most of her time researching technology and startups.

(5.0) | 18924 Ratings 2265
    • In this article you will learn:
    • Access list items
    • Change list items
    • Add list items
    • Remove list items
    • Looping through a list
    • Sorting python lists
    • Copy lists
    • Join lists
    • List of lists

Access list items

To access a list item in Python, just use the list’s name followed by the item’s index (offset) within square brackets, just as you would with a string. If you want to get to the last few items in the list, you can use a negative offset. The image below demonstrates the structure of a basic Python list and its contents.

Example 1: Accessing List Items

  • List1 = [‘Python’, 3.0, ‘yyyyy’, ‘Python Courses’]
  • print(List1[0]) #Python
  • print(List1[2]) #yyyy Learning
  • print(List1[-1]) #Python Courses

Lists in Python are zero-indexed, meaning that the first item in a list has an index of 0. Python will throw an IndexError if you try to use an index that is not inside the range of the list.

Example 2: Accessing an index outside the bounds

  • List1 = [‘Python’, 3.0, ‘yyyy’, ‘Python Courses’]
  • print(List1[-5]) ## IndexError: list index out of range

Change list items

Lists in Python are zero-indexed, meaning that the first item in a list has an index of 0. Python will throw an IndexError if you try to use an index that is not inside the range of the list.

Example 3: Changing List Items:

  • List1 = [‘Python’, 2.0, ‘yyyyy’, ‘Python Courses’]
  • print(“Original List:”, List1)
  • List1[1] = 3.0
  • List1[-1] = ‘Python Certifications’
  • print(“Updated List:”, List1)

Either a single item in the list (through offset) or the full list may have its contents modified (slicing). Slicing allows for the wholesale replacement of a given string’s substring in a single action.

Example 4: Changing a section of list:

  • List1 = [‘Python’, 2.0, ‘yyyyy’, ‘Python Certifications’]
  • print(“Original List:”, List1)
  • List1[1:3] = [3.0, ‘Python Online Courses’, ‘yyyyy’]
  • print(“Updated List:”, List1)

Index and slice assignments both modify the list while it is already in existence, as opposed to creating a new list object. Utilizing list methods like insert, pop, and remove, you may also change lists.

Add list items

There are several ways to include an element in the list. Utilizing the indexing or slicing assignments, you can add an item to a specific index. You can also use the built-in Python list methods as an alternative. Let’s examine each of these using straightforward examples.

Adding an item using append()

You can add an element at the end of the list using the append() method as shown below.

Example 5: Adding item to list using append()

  • List1 = [1, 2, 3]
  • print(“Original List:”, List1)
  • List1.append(‘abc’)
  • print(“Update version 1 of List:”, List1)
  • List2 = [‘ABCD’, ‘WXYZ’]
  • List1.append(List2)
  • print(“Update version 2 of List:”, List1)

A single element is added to the end of the existing list if you attempt to attach another list. In the aforementioned illustration, List2 [‘ABCD,’ ‘WXYZ’] becomes List1’s final element.

Adding an item using insert():

You can use the insert(index, value) method, as illustrated below, to add an element at a specific index.

Example 6: Adding item to list using insert(index, value)

  • List1 = [1, 2, 3]
  • print(“Original List:”, List1)
  • List1.insert(0, ‘abc’)
  • print(“Update version 1 of List:”, List1)
  • List2 = [‘ABCD’, ‘WXYZ’]
  • List1.insert(10, List2)
  • print(“Update version 2 of List:”, List1)

You’ll see that I specified offset in the second section of the code as 10, which is past the list’s end. It should raise an exception in an obvious sense, but it doesn’t. The new element is simply added to the end of the list using the insert function.

Remove list items

Deleting list items using pop()

The pop() function allows you to simultaneously delete and retrieve an item from a list. If the offset is given, the items at that offset are returned and removed. Pop() returns and deletes the final entry of the list when no argument is provided.

Example 7: Deleting an item using pop()

  • List1 = [1,’ABC’, 2, 3, ‘abc’, ‘XYZ’]
  • print(“Original List:”, List1)
  • print(“Removed element:”, List1.pop(1))
  • print(“Update version 1 of List:”, List1)
  • print(“Next removed element:”, List1.pop())
  • print(“Update version 2 of List:”, List1)

Deleting list items using remove():

Using the remove() function, you may delete an item by value as seen below. This technique eliminates the first instance of the value you provide.

Example 8: Deleting an item using remove

  • List1 = [1,’ABC’, 2, ‘XYZ’, 3, ‘abc’, ‘XYZ’]
  • print(“Original List:”, List1)
  • print(“Removed element:”, List1.remove(‘XYZ’))
  • print(“Update version of List:”, List1)

Deleting list items using del:

You may remove an element at a certain offset with the Python command del. It’s important to emphasise that it’s not a technique.

Example 9: Deleting an item using keyword del

  • List1 = [1,’ABC’, 2, ‘XYZ’, 3, ‘abc’, ‘XYZ’]
  • print(“Original List:”, List1)
  • del List1[5:7]
  • print(“Update version of List:”, List1)

Looping through a list

Method 1: Using for loop

Using looping mechanisms, particularly for loop, is the most typical method of traversing a list. Here is an easy illustration.

Example 10: Looping through a list: for loop

  • List1 = [1,’ABC’, 2, ‘XYZ’, 3, ‘abc’, ‘XYZ’]
  • for items in List1:
  • print(items)

If you only want to read the list’s components, this is effective. The indices are now required if you want to change any of the list’s elements. Using range and len, as shown below, is a very popular way to accomplish that.

Method 2: Using for loop, range(), & len()

Example 11: Looping through a list: for loop using range & len

  • List1 = [1, 2, 3, 4, 5, 6]
  • for i in range(len(List1)):
  • List1[i] = List1[i] * List1[i]
  • print(“Update version of List:”, List1)

The for loop iterates through each element in this situation and updates it. The range function returns a list of indices from 0 to n-1 and the len function returns the length of the list “n”.

Method 3: Using while loop

Let’s try using a while loop to print each element and its corresponding offset.

Example 12: Looping through a list: while loop

  • List1 = [1,’ABC’, 2, ‘XYZ’, 3, ‘abc’, ‘XYZ’]
  • i = 0
  • while i < len(List1):
  • print(f'{i}: {List1[i]}’)
  • i = i + 1

Method 4: Using Python enumerate() method

You may sometimes wish to maintain track of both the element and the index. In these circumstances, you may iterate any sequence type using the enumerate method. An iterable is given a counter via the enumerate() function, which also gives back an enumerate object. The key benefit of this method is that you can use list() and tuple() to convert enumerated objects to lists or tuples, respectively.

Syntax: enumerate(iterable, start), where start is the number at which the enumerate begins counting and iterable is the kind of sequence we wish to explore. The default value is zero if omitted.

Example 13: Looping through a list: using enumerate() method

  • List1 = [1,’ABC’, 2, ‘XYZ’, 3, ‘abc’, ‘XYZ’]
  • for i, res in enumerate(List1):
  • print (i,”:”,res)

Sorting python lists

Sorting using sort() function:

You may sometimes wish to maintain track of both the element and the index. In these circumstances, you may iterate any sequence type using the enumerate method. An iterable is given a counter via the enumerate() function, which also gives back an enumerate object. The key benefit of this method is that you can use list() and tuple() to convert enumerated objects to lists or tuples, respectively.

Syntax: enumerate(iterable, start), where start is the number at which the enumerate begins counting and iterable is the kind of sequence we wish to explore. The default value is zero if omitted.

Example 14: Change the default sorting order

  • numbers = [3, 5, 6, 7.5, 2, 1.6]
  • print(“Original list:”, numbers)
  • numbers.sort(reverse = True)
  • print(“Sorted list:”, numbers)
  • strings = [‘jam’, ‘Sam’, ‘ham’, ‘dam’]
  • print(“Original list:”, strings)
  • strings.sort()
  • print(“Sorted list:”, strings) #Mixed sorting
  • strings.sort(key=str.lower)
  • print(“Sorted list:”, strings) #Normalize to lowercase
  • strings.sort(key=str.lower, reverse = True)
  • print(“Sorted list:”, strings) #Normalize to lowercase & change the default sort order

As you can see, the reverse option enables you to arrange things differently from how they are typically sorted: In descending order. A one-argument function (str.lower) that returns the value to be utilised for sorting may also be specified.

Sorting using sorted() function

A sorted copy of the list will be returned if you instead use the sorted() method. It does not change the original list, in contrast to sort().

Example 15: Sorting using sorted()

  • strings = [‘jam’, ‘Sam’, ‘ham’, ‘dam’]
  • print(“Original list before sorting:”, strings)
  • print(“Sorted Copy of List”, sorted(strings))
  • print(“Original list after sorting:”, strings)

Copy lists

When you use default assignment “=”, it ties the new name to a reference to the old list. What you don’t want is for the old name and the new name to both link to the same list. The following methods may be used if you wish to duplicate a list.

Example 16: Copying List

  • actual_str = [‘jam’, ‘Sam’, ‘ham’, ‘dam’]

Method 1: Copying by slicing

  • new_str1 = actual_str[:]

Method 2: Copying using built-in function list

  • new_str1 = list(actual_str)

Method 3: Copying using generic copy.copy()

  • import copy new_list = copy.copy(actual_str)

Join lists

There are many ways to join and concatenate lists. Let’s examine a few of them.

Example 17: Joining Lists

<
  • List1 = [‘jam’, ‘Sam’]
  • List2 = [‘ham’, ‘dam’]

Method 1: Using + operator

  • List3 = List1 + List2
  • print(List3)

Method 2: Using append()

  • for x in List2:
  • List1.append(x)
  • print(List1)

Method 3: Using extend(), which just adds items to end of list

  • List1 = [‘jam’, ‘Sam’]
  • List2 = [‘ham’, ‘dam’]
  • print(List1.extend(List2))

List of lists

As you may already be aware, a list may include components of any kind, including those from other lists. Therefore, a nested list or two-dimensional list is a list inside a list.

  • #using append()
  • res_lst = []
  • res_lst.append(List1)
  • res_lst.append(List2)
  • res_lst.append(List3)
  • print(res_lst)
  • #using list comprehensions (or you can use for loops)
  • l1 = [1, 2, 3]
  • lst = [l1 for i in range(3)]
  • print(lst)

Are you looking training with Right Jobs?

Contact Us

Popular Courses