Python List

A list is one of the built-in data structures in Python that allows you to store a collection of items in a single variable. Lists are ordered and mutable, which means that you can change the order of the elements and add or remove elements from the list. Here’s an example of creating a list in Python:

my_list = [1, 2, 3, 4, 5]

Hence, a list is more versatile and useful than an array.

  • In list, elements or items are separated with the comma (,) and enclosed within the square brackets[].
  • List allows us to store different types of values in a single unit.
  • List can store duplicates items.
  • We can process elements by indexing and slicing. Indexing return only single element whereas slicing can return multiple elements.

Empty List

student = []

Example – To store a student’s information:

student = [1, 'Kumud', 'F', 50, 60, 55, 69, 70]

Example – A python program to create lists having different types of elements:

#create a list with integers
number = [1, 4, 6, 10, 20, 29]
print('Total List ', number)
print('First = %d, Last = %d' % (number[0], number[-1]))

#create a list with strings
strings = ["Meera", "Seeta", "Radha", "Laxmi"]
print('Total List', strings)
print('First = %s, Last = %s' %(strings[0], strings[-1]))

#create a list with different elements
mixed_list = [2, 33, 20.5, "Geeta", "Deepak", [1,2,3,4,5]]
print('Total List', mixed_list)
print('First = %d, Last = %s' % (mixed_list[0], mixed_list[-1]))

#Output
Total List  [1, 4, 6, 10, 20, 29]
First = 1, Last = 29

Total List ['Meera', 'Seeta', 'Radha', 'Laxmi']
First = Meera, Last = Laxmi

Total List [2, 33, 20.5, 'Geeta', 'Deepak', [1, 2, 3, 4, 5]]
First = 2, Last = [1, 2, 3, 4, 5]

Creating List using range() function

A sequence of integers can be stored in a list by using the range() function in python.

range(start, stop, stepsize)
  • Start : Default value of start is 0.
  • stepsize : Default value of stop is 1.
for i in range(1, 10):
        print(i)

#Output
1
2
3
4
5
6
7
8
9

Accessing the List item

In Python, there are several ways to access elements of a list.

List Index: We can use the index operator [] to access an element in a list. Index starts at 0 in python. Index value should in integer otherwise it will raise an “Index Error” or type error. We can supply float or other data type except integer.

my_list = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
print(my_list[0])
print(my_list[3])

#Output
t
o

Nested List Example

my_list = ["Share Query", [3, 12, 9, 20, 2]]
print(my_list[0])
print(my_list[1][3])

#Output
Share Query
20

Negative Indexing Example : The index of -1 refers to the last element of a list. -2 is considered second last element of a list and so on.

my_list = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
print(my_list[-1])
print(my_list[-5])

#Output
l
o

Slicing in List

In python, slicing is used to access a range of items in a list by using slicing operator (:).

my_list = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']

#Elements beginning to end
print(my_list[:])

#Elements 3th to 4th:
print(my_list[2:4])

#Elements beginning to to 4th:
print(my_list[:4])

#Elements 5th to end:
print(my_list[4:])

#Output
['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
['t', 'o']
['t', 'u', 't', 'o']
['r', 'i', 'a', 'l']

Add or change List elements

Lists are mutable. It means list elements can be changed unlike strings and tuple. Assignment (=) symbol is used to change an item or a range of items.

Let us understand with an example:

my_list = ['t', 'u', 't', 'u', 'r', 'i', 'a', 'l']

#correcting mistaken values in my_list
my_list[3] = 'o'
print(my_list)

#Output
['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']

Append() : Can add a single item to a list.

odd_number = [1, 3, 5, 7, 9]
odd_number.append(11)

print(odd_number)

#Output
[1, 3, 5, 7, 9, 11]

Extent() : Can add multiple items to a list.

odd_number = [1, 3, 5, 7, 9]
odd_number.extend(11, 13, 15, 17)

print(odd_number)

#Output
[1, 3, 5, 7, 9, 11, 13, 15, 17]

Concatenation of two lists

By using + operator in python, two lists can be combine together to form a single list. The * operator is used to repeats the list for the given number of times.

#concatenating and repeating list
odd_numbers = [1,3,5,7,9]
print(odd_numbers+[11,13])

#Output
[1, 3, 5, 7, 9, 11, 13]

Insert() method

In list, we can insert one item at a desired location by using insert() method. Also we can insert multiple items by squeezing it into an empty slice of a list.

odd_numbers = [1,3,5,7,9]
odd_numbers.insert(5,11)
print(odd_numbers)

odd_numbers[6:2] = [13, 15]
print(odd_numbers)

#Output
[1, 3, 5, 7, 9, 11]
[1, 3, 5, 7, 9, 11, 13, 15]

Deleting or Removing List Elements

We can delete one or more item from a list using ‘del’ keyword. We can delete the entire list using ‘del’ keyword.

my_list = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']

#delete one item from list
del my_list[2]
print(my_list)

#delete one item from list
del my_list[1:3]
print(my_list)

#delete entire list
del my_list
print(my_list)

#Output 
['t', 'u', 'o', 'r', 'i', 'a', 'l']
['t', 'r', 'i', 'a', 'l']
Traceback (most recent call last):
  File "strings_character.py", line 13, in <module>
    print(my_list)
NameError: name 'my_list' is not defined

  • We can use remove() method to remove the given item or pop() method to remove an item from the end, if the index is given in pop() method then specified index value will be delete.
  • The pop() method remove and return the last item. This process is similar to stack process (FILO).
  • We can use clear() method to empty a list.

IN keyword with List

fruits = ["mango", "apple", "guava", "banana"]
if 'mango' in fruits:
        print("mango is present")
else:
        print("mango is not present")

#Output
mango is present

Other List Methods

  • append()
  • extend()
  • insert()
  • remove()
  • pop()
  • clear()
  • index()
  • count()
  • sort()
  • reverse()
  • copy()
Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial