Python Lists [ ]

Python Lists [ ]

Namaste Coders!

Back with another topic, in this article, we will discover the inbuilt functions of a list🤟.

What is List?

List is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ].

Lists can consist of both homogeneous and heterogeneous values.

An empty list is defined as:

# Lists in Python
# Empty List
l1=[ ]
l2=list()
print(l1)  #[ ]
print(l2)  #[ ]
arr = ["a", "b", "c", 4, 7]
print(arr)  #['a', 'b', 'c', 4, 7]
print(type(arr))  #<class 'list'>

myList = list ((1,2,3,4,5))
print(myList)  #[1, 2, 3, 4, 5]
print(type(myList))  #<class 'list'>

Lists are great to use when you want to work with many values. It allows you to keep data together that belongs together, condense your code, and perform the operations on multiple values at once.

Lists are iterable which means we can loop it and also we can get individual elements from a list by indexing.

arr = ["a", "b", "c", "d", "e"]

for i in arr:
    print(i)

# a
# b
# c
# d
# e
arr = ["a", "b", "c", "d", "e"]

for i in range(len(arr)):
    # accessing the value using index value
    print(i , arr[i])

# 0 a
# 1 b
# 2 c
# 3 d
# 4 e

Indexing

Each item in a list corresponds to an index number, which is an integer value, starting with the index number 0.

image.png

Lists also follow negative indexing from right to left beginning from -1.

Negative Indexing

image.png

## Indexing
fruits=["apple","kiwi","banana","mango"]
print("fruit at index 0: ",fruits[0])
print("fruit at index 1: ",fruits[1])
print("fruit at index 2: ",fruits[2])
print("fruit at index 3: ",fruits[3])

## Negative Indexing
print("fruit at index -1: ",fruits[-1])
print("fruit at index -2: ",fruits[-2])
print("fruit at index -3: ",fruits[-3])
print("fruit at index -4: ",fruits[-4])

Output fruit at index 0: apple fruit at index 1: kiwi fruit at index 2: banana fruit at index 3: mango fruit at index -1: mango fruit at index -2: banana fruit at index -3: kiwi fruit at index -4: apple

Modifying List

As lists are mutable so we can easily change the value of an element in a list as shown in the example below👇

# Modifying a list
fruits=["apple","kiwi","banana","mango"]
print("Original List")
print(fruits)
fruits[0]="guava"
print("Updated List:")
print(fruits)

Output

Original List ['apple', 'kiwi', 'banana', 'mango'] Updated List: ['guava', 'kiwi', 'banana', 'mango']

Slicing

Slicing is a very fun loving technique of lists. It allows us to fetch a part from list. We just slice it of. We can use both negative and positive indexing in it.end_index is exclusive whereas start_index is inclusive.

syntax

list_name[start_index:end_index:space]
# slicing
fruits=["apple","kiwi","banana","mango"]
print(fruits[0:2])

num=[1,2,3,4,5,6,7,8]
# It will print all odd numbers as it will skip one element as space=2
print(num[0:8:2])

# It will provide multiples of 3 as space is 3 
print(num[2:8:3])

# slicing from backwards
print(num[-4:-1])

Output

['apple', 'kiwi'] [1, 3, 5, 7] [3, 6] [5, 6, 7]

Built-in List Functions

Some of the useful built-in list functions are 👇

  • list.append(elem) – Adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
fruits=["apple","kiwi","banana","mango"]
fruits.append("pineapple")
print(fruits)
#  ['apple', 'kiwi', 'banana', 'mango', 'pineapple']
  • list.insert(index, elem) Inserts the element at the given index, shifting elements to the right.
fruits=["apple","kiwi","banana","mango"]
fruits.insert(2,"guava")
print(fruits)

#  ['apple', 'kiwi', 'guava', 'banana', 'mango']
  • list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
fruits=["apple","kiwi","banana","mango"]
more_fruits=["litchi","watermelon","plum"]
fruits.extend(more_fruits)
print(fruits
['apple', 'kiwi', 'banana', 'mango', 'litchi', 'watermelon', 'plum']
  • list.index(elem) searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use ”in” to check without a ValueError).
fruits=["apple","kiwi","banana","mango"]
fruits.index("kiwi")  #1

fruits.index("tomato")

#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# ValueError: 'tomato' is not in list
  • list.remove(elem) searches for the first instance of the given element and removes it (throws ValueError if not present)
fruits=["apple","kiwi","banana","mango"]
fruits.remove("apple")
fruits
#  ['kiwi', 'banana', 'mango']
  • list.sort()
    sorts the list in place (does not return it). (The sorted() function shown below is preferred.)
fruits=["apple","kiwi","banana","mango"]
fruits.sort()
print(fruits)
#  ['apple', 'banana', 'kiwi', 'mango']
fruits.sort(reverse=True)
print(fruits)
#  ['mango', 'kiwi', 'banana', 'apple']
  • list.reverse() reverses the list in place (does not return it)
fruits=["apple","kiwi","banana","mango"]
fruits.reverse()
print(fruits)
# ['mango', 'banana', 'kiwi', 'apple']
  • list.pop(index)

removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).

fruits=["apple","kiwi","banana","mango"]
print(fruits.pop())

#  'mango'

print(fruits)
# ['apple', 'kiwi', 'banana']

print(fruits.pop(2))
#  'banana'

print(fruits)
#  ['apple', 'kiwi']
  • list.count(x) Returns the number of times x appears in the list.
fruits=["apple","kiwi","banana","mango","apple"]
print(fruits.count("apple"))  #2

print(fruits.count("kiwi"))  #1

List Comprehension

It is an advance way and shorthand syntax of creating a new list from existing values.

Syntax

newList = [ expression(element) for element in oldList if condition ]

iterating in list comprehension

# to make a list of squares
l=[i*i for i in range(1,10)]
print(l)
#  [1, 4, 9, 16, 25, 36, 49, 64, 81]

num="10,20,30,40,50"
numbers=[int(no) for no in num.split(',')]
print(numbers)
#[10, 20, 30, 40, 50]

using if in list comprehension

#creating a list containing even values
list = [i for i in range(11) if i % 2 == 0]
print(list)

#[0, 2, 4, 6, 8, 10]

if and else in list comprehension

lis = [i**2 if i % 2 == 0 else i**3 for i in range(5)]
print(lis)

#[0, 1, 4, 27, 16]

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharing👩

Keep coding

Python blogs

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg by becoming a sponsor. Any amount is appreciated!