Python - Remove List Items,Python - Loop Lists Python - List Comprehension,Sort List Alphanumerically,Python - Copy Lists

 

Remove Specified Item

The remove() method removes the specified item.

Example

Remove "banana":

thislist = ["apple""banana""cherry"]
thislist.remove("banana")
print(thislist)
Try it Yourself »

Remove Specified Index

The pop() method removes the specified index.

Example

Remove the second item:

thislist = ["apple""banana""cherry"]
thislist.pop(1)
print(thislist)
Try it Yourself »

If you do not specify the index, the pop() method removes the last item.

Example

Remove the last item:

thislist = ["apple""banana""cherry"]
thislist.pop()
print(thislist)
Try it Yourself »

The del keyword also removes the specified index:

Example

Remove the first item:

thislist = ["apple""banana""cherry"]
del thislist[0]
print(thislist)
Try it Yourself »

The del keyword can also delete the list completely.

Example

Delete the entire list:

thislist = ["apple""banana""cherry"]
del thislist
Try it Yourself »

Clear the List

The clear() method empties the list.

The list still remains, but it has no content.

Example

Clear the list content:

thislist = ["apple""banana""cherry"]
thislist.clear()
print(thislist)
Try it Yourself »

Loop Through a List

You can loop through the list items by using a for loop:

Example

Print all items in the list, one by one:

thislist = ["apple""banana""cherry"]
for x in thislist:
  print(x)
Try it Yourself »

Learn more about for loops in our Python For Loops Chapter.


Loop Through the Index Numbers

You can also loop through the list items by referring to their index number.

Use the range() and len() functions to create a suitable iterable.

Example

Print all items by referring to their index number:

thislist = ["apple""banana""cherry"]
for i in range(len(thislist)):
  print(thislist[i])
Try it Yourself »

The iterable created in the example above is [0, 1, 2].


ADVERTISEMENT

Using a While Loop

You can loop through the list items by using a while loop.

Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by refering to their indexes.

Remember to increase the index by 1 after each iteration.

Example

Print all items, using a while loop to go through all the index numbers

thislist = ["apple""banana""cherry"]
i = 0
while i < len(thislist):
  print(thislist[i])
  i = i + 1
Try it Yourself »

Learn more about while loops in our Python While Loops Chapter.


Looping Using List Comprehension

List Comprehension offers the shortest syntax for looping through lists:

Example

A short hand for loop that will print all items in a list:

thislist = ["apple""banana""cherry"]
[print(x) for x in thislist]
Try it Yourself »

Python - List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.

Without list comprehension you will have to write a for statement with a conditional test inside:

Example

fruits = ["apple""banana""cherry""kiwi""mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.append(x)

print(newlist)
Try it Yourself »

With list comprehension you can do all that with only one line of code:

Example

fruits = ["apple""banana""cherry""kiwi""mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
Try it Yourself »

ADVERTISEMENT

The Syntax

newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.


Condition

The condition is like a filter that only accepts the items that valuate to True.

Example

Only accept items that are not "apple":

newlist = [x for x in fruits if x != "apple"]
Try it Yourself »

The condition if x != "apple"  will return True for all elements other than "apple", making the new list contain all fruits except "apple".

The condition is optional and can be omitted:

Example

With no if statement:

newlist = [x for x in fruits]
Try it Yourself »

Iterable

The iterable can be any iterable object, like a list, tuple, set etc.

Example

You can use the range() function to create an iterable:

newlist = [x for x in range(10)]
Try it Yourself »

Same example, but with a condition:

Example

Accept only numbers lower than 5:

newlist = [x for x in range(10if x < 5]
Try it Yourself »

Expression

The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list:

Example

Set the values in the new list to upper case:

newlist = [x.upper() for x in fruits]
Try it Yourself »

You can set the outcome to whatever you like:

Example

Set all values in the new list to 'hello':

newlist = ['hello' for x in fruits]
Try it Yourself »

The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome:

Example

Return "orange" instead of "banana":

newlist = [x if x != "banana" else "orange" for x in fruits]
Try it Yourself

List objects have a sort() method that will sort the list alphanumerically, ascending, by default:

Example

Sort the list alphabetically:

thislist = ["orange""mango""kiwi""pineapple""banana"]
thislist.sort()
print(thislist)
Try it Yourself »

Example

Sort the list numerically:

thislist = [10050658223]
thislist.sort()
print(thislist)
Try it Yourself »

Sort Descending

To sort descending, use the keyword argument reverse = True:

Example

Sort the list descending:

thislist = ["orange""mango""kiwi""pineapple""banana"]
thislist.sort(reverse = True)
print(thislist)
Try it Yourself »

Example

Sort the list descending:

thislist = [10050658223]
thislist.sort(reverse = True)
print(thislist)
Try it Yourself »


Customize Sort Function

You can also customize your own function by using the keyword argument key = function.

The function will return a number that will be used to sort the list (the lowest number first):

Example

Sort the list based on how close the number is to 50:

def myfunc(n):
  return abs(n - 50)

thislist = [10050658223]
thislist.sort(key = myfunc)
print(thislist)
Try it Yourself »

Case Insensitive Sort

By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters:

Example

Case sensitive sorting can give an unexpected result:

thislist = ["banana""Orange""Kiwi""cherry"]
thislist.sort()
print(thislist)
Try it Yourself »

Luckily we can use built-in functions as key functions when sorting a list.

So if you want a case-insensitive sort function, use str.lower as a key function:

Example

Perform a case-insensitive sort of the list:

thislist = ["banana""Orange""Kiwi""cherry"]
thislist.sort(key str.lower)
print(thislist)
Try it Yourself »

Reverse Order

What if you want to reverse the order of a list, regardless of the alphabet?

The reverse() method reverses the current sorting order of the elements.

Example

Reverse the order of the list items:

thislist = ["banana""Orange""Kiwi""cherry"]
thislist.reverse()
print(thislist)
Try it Yourself »

You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.

There are ways to make a copy, one way is to use the built-in List method copy().

Example

Make a copy of a list with the copy() method:

thislist = ["apple""banana""cherry"]
mylist = thislist.copy()
print(mylist)
Try it Yourself »

Another way to make a copy is to use the built-in method list().

Example

Make a copy of a list with the list() method:

thislist = ["apple""banana""cherry"]
mylist list(thislist)
print(mylist)
Try it Yourself »

Post a Comment

0 Comments