Lists in Python

Lists in Python

# ============================
# Lits
# in lists every element can be of different type

letters = ["a", "b", "c"]
matrix = [[1,2], [3,4]]

# repeating items in a list 
print ([0] * 10)
# this will print [0,0,0,0,0,0,0,0,0,0]

# concating lists 
zeros = [0] * 5
combined  = zeros + letters

# the lists function
numbers = list(range(20))       # as the range function gives an itterable 
# this will create a list from 0 to 19

char = list("harshit saini")

Accessing the elements

[0]   # access 0th element
[-1]  # access 1st element from the last 
[0:3]  # from elements from 0 to 2
[:3]  # from 0 to 2
[0:]  # from 0 to end
[:]  # from 0 to end

[::2]  # from 0 to end and every 2nd element only

[::-1]  # get all items in reverse order

List Unpacking

like object destructuring in js

numbers = [1,2,3]
first, second, third = numbers

# the number of variables on the left 
# should be equal to numbers of elements in the list

first, *others  = numbers
# we get the first and every thing 
# else is packed inside others list

# this is called packing 

first, *other, last = numbers
# this is how we can take the first and the last element

Looping over the list

l = list("harshit-saini")
for ch in l:
    print(ch)

# this way the ch will have only elements in the list
# and it will print only the element

l = list("harshit-saini")
for ch in enumerate(l):
    print(ch)
        print ("index is" , ch[0])
        print ("element is ", ch[1])

# this way ch will be a tuple which contains the 
# index and the element itself

Adding and removing items

# adding and removing items 
g = [1,2,3,4,5]

g.append(10)        # adding to the last
g.insert(0, 10)      # inserting 10 at index 0

g.pop()         # remove the last element
g.pop(0)     # remove element fron index 0
g.remove(1)       # remove 1 from the list (first occurance)
                  # to remove all occurance we have to loop over the list

del g[0:3]      # remove a range of items from 0 to 2
del g[0]        # delete the item at index 0

Finding elements in a list

index = g.index(1)      # get the index of 1

# note : in python if the element is not in the list and we try to print the index, we get error
#  so fist we should check if the element is there and then we should find the index 

if 1 in g:
    print (g.index(1))

Counting elements

fre = g.count(12)

# this will count how many times 12 occurred in the list

Sorting List

numbers.sort()    # this sorts in ass order

numbers.sort(reverse="True")  # dess order

we can also use the built in function sorted( ). This function takes iterables as arguments. This returns a new sorted list.

new_sorted_list= sorted (numbers_list, reverse="True"

Sometimes we have to create our own sorting function to sort list like these

items = [
("Product", 10),
("Product", 9),
("Product", 12),
]

items.sort()     # this will do nothing

# we have to make a function 
def sort_item(item): 
    return item[1]

# now give this function to the sort function
items.sort(key=sort_item)  # we do not have to call this function

Using Lamda Function

syntax is => lamda parameters:expression

items.sort( key=lamda item:item[1] )
# we do not need the return keyword

Did you find this article valuable?

Support Harshit Saini by becoming a sponsor. Any amount is appreciated!