Lists In Python

Lists In Python

·

11 min read

Hey techies, I wish you have a good day today, welcome to this week's article. Today, I am going to make you gain knowledge on "data types". If you are new to Python programming then this will help you flaunt your coding skills among your peers. Hope you are loving my articles and I appreciate it if you show a response by commenting, liking or even sharing on your socials. I am focusing more on Python so I also suggest you to read my previous articles on Python.

What is list in Python?

Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). In simple language, a list is a collection of things, enclosed in [ ] and separated by commas.

A single list may contain DataTypes like Integers, Strings, as well as Objects.

Lists are mutable, and hence, they can be altered even after their creation.

The list is a sequence data type which is used to store the collection of data. Tuples and String are other types of sequence data types.

Var = ["Hello", 1,1.6,1+6j,"'neighbour'","Friend"]
print(Var)

Output: #see the difference
['Hello', 1, 1.6, (1+6j), "'neighbour'", 'Friend']

Performing Slicing in Lists:

# Creating a List of strings and accessing
# using index
List = ["lion", "met", "king"]
print("\nList Items: ")
print(List[0])
print(List[2])

Output:
List Items: 
lion
king

Example 2: Creating a list with multiple distinct or duplicate elements.

A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values can be passed as a sequence at the time of list creation.

# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)

# mixed type of values
# (Having numbers and strings)
List = [1, 2, 'lion', 4, 'meets', 6, 'tiger']
print("\nList with the use of Mixed Values: ")
print(List)

Output:   
List with the use of Numbers: [1, 2, 4, 4, 3, 3, 3, 6, 5]
List with the use of Mixed Values: [1, 2, 'lion', 4, 'meets', 6, 'tiger']

Example 3: Accessing elements from a multi-dimensional list.

# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['HEY', 'Nature','is'], ['BEAUTIFUL']]

# now in this multi dimension list "hey --- look" is index 0 and" Beautiful" is index 1.
print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
#access the  0 th index from the whole list from the 0 th index access the 1st index
print(List[1][0])
#access the 1st index from the whole list from the 0th index access the 1st index.

Output:
Accessing a element from a Multi-Dimensional list
Nature
BEAUTIFUL

Negative indexing

In Python, negative sequence indexes represent positions from the end of the array.

  • It is enough to just write List[-3].

  • Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.

List = [1, 2, 'one+two', 4, 'Four', 6, 'Six']

# accessing an element using
# negative indexing
print("Accessing element using negative indexing")

# print the last element of list
print(List[-1])

# print the third last element of list
print(List[-3])

Ouput:
Accessing element using negative indexing
Six
Four

Getting the size of Python list

Python len() is used to get the length of the list.

# Creating a List
List1 = []
print(len(List1))

# Creating a List of numbers
List2 = [10, 20, 14]
print(len(List2))

Output:
0
3

Taking Input of a Python List

We can take the input of a list of elements as string, integer, float, etc. But the default one is a string.

  • split() is a key word function in lists which will seperate the given inputs into seperate lists and prints it.

Example 1:

# Python program to take space
# separated input as a string
# split and store it to a list
# and print the string list

# input the list as string.
string = input("Enter elements (Space-Separated): ")

# split the strings and store it to a list
lst = string.split()
print('The list is:', lst) # printing the list
print(len(lst))

Input:
#giving a statement as a input :: "Mars is a red planet"
Output:
The list is: ['Mars', 'is', 'a', 'red', 'planet']
5

Adding Elements to a Python List

Method 1: Using append() method

Elements can be added to the List by using the built-in append() function.

Only one element at a time can be added to the list by using the append() method, for the addition of multiple elements with the append() method, loops are used.

We can also add tuples into the list with the use of the append method because tuples are immutable. Unlike Sets, Lists can also be added to the existing list with the use of the append() method.

# Python program to demonstrate
# Addition of elements in a List

# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

#usinf=g loops
for i in range(1, 4):
    List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)

# Adding Tuples to the List
List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)

# Addition of List-2 to a List
List2 = ['Once', 'there']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)

Output:
Initial blank List: 
[]

List after Addition of Three elements: 
[1, 2, 4]

List after Addition of elements from 1-3: 
[1, 2, 4, 1, 2, 3]
List after Addition of a Tuple: 
[1, 2, 4, 1, 2, 3, (5, 6)]

List after Addition of a List: 
[1, 2, 4, 1, 2, 3, (5, 6), ['Once', 'there']]

Method 2: Using insert() method

append() method only works for the addition of elements at the end of the List, for the addition of elements at the desired position, insert() method is used. Unlike append() which takes only one argument, the insert() method requires two arguments(position, value).

# Python program to demonstrate
# Addition of elements in a List

# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)

# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Lamborghini')
print("\nList after performing Insert Operation: ")
print(List)

Output:
Initial List: 
[1, 2, 3, 4]

List after performing Insert Operation: 
['Lamborghini', 1, 2, 3, 12, 4]

Method 3: Using extend() method

Other than append() and insert() methods, there’s one more method for the Addition of elements, extend(), this method is used to add multiple elements at the same time at the end of the list.

Note: append() and extend() methods can only add elements at the end.

# Creating a List
List = [1, 2, 3, 4]
print("Initial List: ")
print(List)

# Addition of multiple elements   ----similar to ADDING [LIST1+LIST2]
# to the List at the end
# (using Extend Method)
List.extend([8, 'Wish', 'Foreign'])  #can add more elements at a time.
print("\nList after performing Extend Operation: ")
print(List)

Reversing a List

A list can be reversed by using the reverse() method in Python.

# Reversing a list
mylist = [1, 2, 3, 4, 5, 'Uber', 'Ola']
mylist.reverse()
print(mylist)


Output:
['Ola', 'Uber', 5, 4, 3, 2, 1]

Removing Elements from the List

Method 1: Using remove() method

Elements can be removed from the List by using the built-in remove() function but an Error arises if the element doesn’t exist in the list. Remove() method only removes one element at a time, to remove a range of elements, the iterator is used. The remove() method removes the specified item.

Note: Remove method in List will only remove the first occurrence of the searched element.

# Creating a List
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)

# Removing elements from List
# using Remove() method
List.remove(5)
List.remove(6)
#throws error if given the element is not in list.
list.remove(90)
print("\nList after Removal of two elements: ")
print(List)

Output:
Initial List: 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
            #ERROR
Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: descriptor 'remove' for 'list' objects doesn't apply to a 'int' object

Method 2: Using pop() method

pop() function can also be used to remove and return an element from the list, but by default it removes only the last element of the list, to remove an element from a specific position of the List, the index of the element is passed as an argument to the pop() method.

List = [1, 2, 3, 4, 5]
# Removing element from the
# Set using the pop() method
List.pop()    #DEFAULT:   removes the last element
print("\nList after popping an element: ")
print(List)

# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(2)    #removes the INDEX position element
print("\nList after popping a specific element: ")
print(List)

Output:
List after popping an element: 
[1, 2, 3, 4]

List after popping a specific element: 
[1, 2, 4]

Slicing of a List

We can get substrings and sublists using a slice. In Python List, there are multiple ways to print the whole list with all the elements, but to print a specific range of elements from the list, we use the Slice operation.

Slice operation is performed on Lists with the use of a colon(:).

To print elements from beginning to a range use:

[: Index]

To print elements from end-use:

[:-Index]

To print elements from a specific Index till the end use

[Index:]

To print the whole list in reverse order, use
[::-1]

UNDERSTANDING SLICING OF LISTS:

  • pr[0] accesses the first item, 2.

  • pr[-4] accesses the fourth item from the end, 5.

  • pr[2:] accesses [5, 7, 11, 13], a list of items from third to last.

  • pr[:4] accesses [2, 3, 5, 7], a list of items from first to fourth.

  • pr[2:4] accesses [5, 7], a list of items from third to fifth.

  • pr[1::2] accesses [3, 7, 13], alternate items, starting from the second item.

# Creating a List
List = ['H', 'E', 'L', 'L', 'O', 'H',
        'O', 'W', 'A', 'R', 'E', 'U']
print("Initial List: ")
print(List)

# Print elements of a range
# using Slice operation
Sliced_List = List[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_List)

# Print elements from a
# pre-defined point to end
Sliced_List = List[5:]
print("\nElements sliced from 5th "
    "element till the end: ")
print(Sliced_List)

# Printing elements from
# beginning till end
Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)

Output:

Initial List: 
['H', 'E', 'L', 'L', 'O', 'H', 'O', 'W', 'A', 'R', 'E', 'U']

Slicing elements in a range 3-8: 
['L', 'O', 'H', 'O', 'W']

Elements sliced from 5th element till the end: 
['H', 'O', 'W', 'A', 'R', 'E', 'U']

Printing all elements using slice operation: 
['H', 'E', 'L', 'L', 'O', 'H', 'O', 'W', 'A', 'R', 'E', 'U']

Negative index List slicing

List = ['H', 'E', 'L', 'L', 'O', 'H',
        'O', 'W', 'A', 'R', 'E', 'U']

print("Initial List: ")
print(List)

# Print elements from beginning
# to a pre-defined point using Slice
Sliced_List = List[-12:-6]  or Sliced_List = List[:-6] 
print("\nElements sliced till 6th element from last: ")
print(Sliced_List)

# Print elements of a range
# using negative index List slicing
Sliced_List = List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)

# Printing elements in reverse
# using Slice operation
Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)

Output:

Initial List: 
['H', 'E', 'L', 'L', 'O', 'H', 'O', 'W', 'A', 'R', 'E', 'U']

Elements sliced till 6th element from last: 
['H', 'E', 'L', 'L', 'O', 'H']

Elements sliced from index -6 to -1
['O', 'W', 'A', 'R', 'E']

Printing List in reverse: 
['U', 'E', 'R', 'A', 'W', 'O', 'H', 'O', 'L', 'L', 'E', 'H']

List Comprehension

Python List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

Syntax:

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

# comprehension in Python
# below list contains square of all
# odd numbers from range 1 to 10
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print(odd_square)

Output:
[1, 9, 25, 49, 81]

For better understanding:

# for understanding, above generation is same as,
odd_square = []

for x in range(1, 11):
    if x % 2 == 1:
        odd_square.append(x**2)

print(odd_square)

Output:
[1, 9, 25, 49, 81]

Built-in functions with List

FunctionDescription
reduce()apply a particular function passed in its argument to all of the list elements stores the intermediate result and only returns the final summation value
sum()Sums up the numbers in the list
ord()Returns an integer representing the Unicode code point of the given Unicode character
cmp()This function returns 1 if the first list is “greater” than the second list
max()return maximum element of a given list
min()return minimum element of a given list
all()Returns true if all element is true or if the list is empty
any()return true if any element of the list is true. if the list is empty, return false
len()Returns length of the list or size of the list
enumerate()Returns enumerate object of the list
accumulate()apply a particular function passed in its argument to all of the list elements returns a list containing the intermediate results

Click here to know more:

Yeah thats for today hope u will utilize it💡 ,lets meet in the next blog Cyaaa🤫"

Success is not finaal, Failure is not fatal, It is the courage to continue that counts.

Did you find this article valuable?

Support Sohail's Blog by becoming a sponsor. Any amount is appreciated!