Invisible link to canonical for Microformats

Lists


Lists

Lists store multiple items in a single variable. They belong to list class.

  • They are ordered by a list like arrays.
  • They allows duplicate values.
  • Items can be changed.
  • Items can be of any data type.
songs = ["Walk", "Of the Night", "Bad Blood"]
print(songs)
# ['Walk', 'Of the Night', 'Bad Blood']

len() displays list length.

print(len(songs)) # 3

list() lets you make a list too.

new_songs = list(("We Are Young", "Take Me to Church", "Soy Yo"))
print(new_songs)
# ['We Are Young', 'Take Me to Church', 'Soy Yo']

You can access list items using their index no.

print(new_songs[1]) # Take Me to Church

We can also use negative indexing [starting from the end instead of beginning].

new_songs = list(("We Are Young", "Take Me to Church", "Soy Yo", "Call It What You Want", "stevie"))
print(new_songs[-2]) # Call It What You Want

You can specify a range of indexes and return a new list with the said range. It goes like this [starting index : end index]

print(new_songs[1:4])
# ['Take Me to Church', 'Soy Yo', 'Call It What You Want']

If starting index isn’t specified, it returns a list from start but ends before end index.

print(new_songs[:3])
# ['We Are Young', 'Take Me to Church', 'Soy Yo']

If ending index isn’t specified, it returns a list starting after starting index.

print(new_songs[2:])
# ['Soy Yo', 'Call It What You Want', 'stevie']

If negative index is used for both starting index and end index, it goes to the required starting index and moves end index steps forward.

print(new_songs[-3:-1])
# ['Soy Yo', 'Call It What You Want']

starting index negative and end index positive returns nothing.

starting index positive and end index negative returns a list starting from starting index but not including end index.

print(new_songs[1:-1])
# ['Take Me to Church', 'Soy Yo', 'Call It What You Want']

Use in operator to check if item exists in the list.

if "Soy Yo" in new_songs:
    print("Soy Yo!") # Soy Yo!

if "Glory" in new_songs:
    print("And all their words for glory")
else:
    print("Well they always sounded empty")
# Well they always sounded empty

Use index number to change the value of items.

new_songs[3] = "Things We Lost in the Fire"
print(new_songs)
"""
['We Are Young', 'Take Me to Church', 'Soy Yo', 'Things We Lost in the Fire', 'stevie']
"""

Specify a range to change a range of item values.

new_songs[1:3] = "Things We Lost in the Fire", "The Nights"
print(new_songs)
"""
['We Are Young', 'Things We Lost in the Fire', 'The Nights', 'Call It What You Want', 'stevie']
"""

If you insert more or less items than you replace, the list will adjust accordingly. Length of list will change.

new_songs[1:3] = ["Things We Lost in the Fire"]
print(new_songs)
print(len(new_songs))
"""
['We Are Young', 'Things We Lost in the Fire', 'Call It What You Want', 'stevie']
4
"""

new_songs[1:3] = ["Things We Lost in the Fire", "Warmth", "Glory"]
print(new_songs)
print(len(new_songs))
"""
['We Are Young', 'Things We Lost in the Fire', 'Warmth', 'Glory', 'Call It What You Want', 'stevie']
6
"""

If you don’t use brackets, it will take each letter as list item.

new_songs[1:3] = "Things We Lost in the Fire"
print(new_songs)
print(len(new_songs))
"""
['We Are Young', 'T', 'h', 'i', 'n', 'g', 's', ' ', 'W', 'e', ' ', 'L', 'o', 's', 't', ' ', 'i', 'n', ' ', 't', 'h', 'e', ' ', 'F', 'i', 'r', 'e', 'Call It What You Want', 'stevie']
29
"""

insert() inserts items at a specific index.

new_songs.insert(3, "Warmth")
print(new_songs)
"""
['We Are Young', 'Take Me to Church', 'Soy Yo', 'Warmth', 'Call It What You Want', 'stevie']
"""

append() adds items to the end of the list.

new_songs.append("Time to Pretend")
print(new_songs)
"""
['We Are Young', 'Take Me to Church', 'Soy Yo', 'Call It What You Want', 'stevie', 'Time to Pretend']
"""

extend() lets you append [add to end of list] items from one list, tuple, dictionaries, etc. to a list.

bastille = ["Warmth", "Glory", "Pompeii"]
mgmt = ["Kids", "Time to Pretend"]
mgmt.extend(bastille)
print(mgmt)
# ['Kids', 'Time to Pretend', 'Warmth', 'Glory', 'Pompeii']

remove() removes the first occurrence of an item.

bastille.remove("Pompeii")
print(bastille) # ['Warmth', 'Glory']

pop() removes the items using their index. If not specified, pop() removes the last item in list.

bastille.pop(1)
print(bastille) # ['Warmth', 'Pompeii']

bastille.pop()
print(bastille) # ['Warmth', 'Glory']

del removes items using index. It can also delete the entire list.

del bastille[0]
print(bastille) # ['Glory', 'Pompeii']


del bastille
print(bastille)
# NameError: name 'bastille' is not defined

clear empties the list.

bastille.clear()
print(bastille) # []

Lists can be looped through a for loop

for i in bastille:
    print(i)
"""
Warmth
Glory
Pompeii
"""

You can also use range() and len() to loop through list using items’ index no.s

for i in range(len(bastille)):
    print(bastille[i])
"""
Warmth
Glory
Pompeii
"""

To loop using while loop, get length of list and start at 0.

i = 0
while i < len(bastille):
    print(bastille[i])
    i+=1
"""
Warmth
Glory
Pompeii
"""

Easiest way is to use list comprehension for looping.

[print(i) for i in bastille]
"""
Warmth
Glory
Pompeii
"""

You can also use conditionals with list comprehension.

listName = [expression for item in list if condition == True]

Only the items passing this condition are added to list.

new_songs = list(("We Are Young", "Take Me to Church", "Soy Yo", "Call It What You Want", "stevie"))
songs = [i for i in new_songs if "e" in i]
print(songs)
# ['We Are Young', 'Take Me to Church', 'stevie']

old_songs = []
for i in new_songs:
    if "e" in i:
        old_songs.append(i)
print(old_songs)
# ['We Are Young', 'Take Me to Church', 'stevie']

new = [i.upper() for i in new_songs]
print(new)
"""
['WE ARE YOUNG', 'TAKE ME TO CHURCH', 'SOY YO', 'CALL IT WHAT YOU WANT', 'STEVIE']
"""

We can create a list using range()

new = [i for i in range(10)]
print(new) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

sort() will sort lists alphanumerically in ascending order.

new_songs = list(("We Are Young", "Take Me to Church", "Soy Yo", "Call It What You Want", "stevie"))
new_songs.sort()
print(new_songs)
"""
['Call It What You Want', 'Soy Yo', 'Take Me to Church', 'We Are Young', 'stevie']
"""

Use reverse=True as argument if list is to be sorted descending order.

new_songs.sort(reverse=True)
print(new_songs)
"""
['stevie', 'We Are Young', 'Take Me to Church', 'Soy Yo', 'Call It What You Want']
"""

key = function can be used to customise sort()

def sortie(n):
    return abs(n - 23)

noveau = [100, 20, 4, 52, 335]
noveau.sort(key = sortie)
print(noveau) # [20, 4, 52, 100, 335]

sort() sorts out capital letters first before going for lower-case. To make it case-insensitive, use key = str.lower

new_songs = list(("We Are Young", "Take Me to Church", "Soy Yo", "Call It What You Want", "stevie"))
new_songs.sort()
print(new_songs)
"""
['Call It What You Want', 'Soy Yo', 'Take Me to Church', 'We Are Young', 'stevie']
"""
new_songs.sort(key = str.lower)
print(new_songs)
"""
['Call It What You Want', 'Soy Yo', 'stevie', 'Take Me to Church', 'We Are Young']
"""

reverse reverses the sorting order.

new_songs.reverse()
print(new_songs)
"""
['stevie', 'Call It What You Want', 'Soy Yo', 'Take Me to Church', 'We Are Young']
"""

copy() lets you copy a list.

mgmt = ["Kids", "Time to Pretend"]
noveau = mgmt.copy()
print(noveau) # ['Kids', 'Time to Pretend']

Slicing also does the same.

noveau = mgmt[:]
print(noveau) # ['Kids', 'Time to Pretend']