Python Lists


Python List

Multiple items are saved in a single variable in lists.

Note :- Lists are created using square brackets.

Example :- A simple list program

mylist = ["London", "Paris", "Berlin"]
print(mylist)

Output :-

['London', 'Paris', 'Berlin']

You can also search for these topics, python lists exercises, what is a python list, what does mean in python list, what is python list and explain features of python, how to print python list, how to create a python list, how to check if python list is empty, example for python list.

List Items

List items are requested, modifiable, and permissible for duplication.

The items in the list are indexed, with the first item having index [0], the second having index [1], and so on.

You can also search for these topics, python list item in another list, check the exist list item in python, how to replace the python list items, check the number of list items with python, update python list item, access python list item.

Ordered

Because once we say that a list is ordered, we indicate that the items are arranged in a specific order that will not change.

The new items will be attached to the end of the list when you add new items to a list.

Note : some processes in the list will change the sequence, but generally : there are no changes in the order of objects.

You can also search for these topics, python ordered list, python ordered dict implementation, example for ordered in python, define the algorithm for ordered, python all ordered compinations, collection and choice with python ordered.

Changeable

The list is changable, that means that after it is created we can change, add and delete items from the list.

You can also search for these topics, python modifiable list, Changeable element in python, example for python changable, how to format the changable in python, define the fields using python changable.

Allow Duplicates

Lists can have the same item value because they are indexed :

Example :- Lists allow duplicate values :

mylist = ["London", "Paris", "Berlin", "Paris"]

print(mylist)

Output :-

['London', 'Paris', 'Berlin', 'Paris']

You can also search for these topics, python allow duplicates keys, python set allow duplicates, do sets allow duplicates python, how to use duplicates zero using python, fill the blanks and allow duplicates with python, Example for python allow duplicates.

List Length

Just use len() function to determine the number of items on a list :

Example :- The total number of items in the list should be printed :

mylist = ["London", "Paris", "Berlin"]
print(len(mylist))

Output :-

3

You can also search for these topics, python list length check, use the limit of python length, how to use attribute with python list length, check the average of list length in python, Example for list length in python.

Check if Item Exists

Using the in keyword, you can check to see if a specific item is in a list of items.

Example :- Check to see if the word "London" appears in the list :

mylist = ["London", "Paris", "Berlin"]
if "London" in mylist:
  print("Yes, 'London' is in the mylist")

Output :-

Yes, 'London' is in the mylist

You can also search for these topics, python check if item exists in two lists, how to check if an item already exists in a list in python, python check if value exists in list, Example for python to check if item existence.

List Items - Data Types

A List can have any type of data in it.

Example 1 :- A simple list with string, int and boolean data types :

list1 = ["London", "Paris", "Berlin"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

print(list1)
print(list2)
print(list3)

Output :-

['London', 'Paris', 'Berlin']
[1, 5, 7, 9, 3]
[True, False, False]

Various data types can be found in a single list.

Example 2 :- Strings, numbers, and boolean values are all included in this list :

list1 = [101, "abc", 20000.50, "male"]

print(list1)

Output :-

[101, 'abc', 20000.50, 'male']

You can also search for these topics, python list item data type and explain, python list the item data type all, list the items based condition using python, how to check list of items in python, ways to change the datatypes with list items using python, python convert the list items in datatypes.

type()

Python defines lists as objects with the data type 'list' from the perspective of Python :

Example :- What type of data does a list contain ?

mylist = ["apple", "banana", "cherry"]

print(type(mylist))

Output :-

<class 'list'>

You can also search for these topics, python type() not working, example for python type(), python type(0 == - python type() arguments, declare the type in python, find the error python type() function, python type without default value.

The list() Constructor

The list() constructors can also be used when a new list is created :

You can also search for these topics, what is the use of list constructor in python, python the list() append constructor, python average list() constructor, python binary search in list() constructor, get the default constructor with python list() function, how to remove the python list() constructor, Example for python list() constructor.

Access List Items

Items in the list are indexed, and you can find them by referring to the index number.

Example :- The second item in the list should be printed :

mylist = ["London", "Paris", "Berlin"]
print(mylist[1])
Paris

Note:- The first item has index 0.

You can also search for these topics, python access multiple list items, python get list item position, access all item in list python, how to access list item in python, python access list element by value, Example for access list items.

Negative Indexing

Indexing in the negative direction means starting from the end.

-1 refers to the last item, -2 refers to the second last item etc.

Example :- The last item in the list should be printed :

mylist = ["London", "Paris", "Berlin"]
print(mylist[-1])

Output :-

Berlin

You can also search for these topics, python negative indexing, start the indexing to be negative, Example for python negative indexing, last item of the list in negative indexing.

Range of Indexes

By selecting where to start and where to end the range, you can specify a range of indexes.

In the case of specifying a range, the return value will be a new list with the items supplied.

Example 1 :- The third, fourth, and fifth items should be returned :

mylist = ["apple", "banana", "grapes", "orange", "papaya", "melon", "mango"]
print(mylist[2:5])

#This will return the items from position 2 to 5.

#Remember that the first item is position 0,
#and note that the item in position 5 is NOT included

Output :-

['grapes', 'orange', 'papaya']

Index 2 (included) is the starting point of the search. Index 5 is the end destination (not included).

Keep in mind that the first item has an index of 0.

The range will extend to the beginnig of the list if the start value is omitted from the syntax :

Example 2 :- "orange" is NOT included in this example, thus it returns the things from the beginning :

mylist = ["apple", "banana", "grapes", "orange", "papaya", "melon", "mango"]
print(mylist[:3])

#This will return the items from index 0 to index 3.

#Remember that index 0 is the first item, and index 3 is the fourth item
#Remember that the item in index 3 is NOT included

Output :-

['apple', 'banana', 'grapes']

The range will extend to the end of the list if the end value is omitted from the formula :

Example 3 :- This example retrieves all of the items from "grapes" through the end of the list of items returned :

mylist = ["apple", "banana", "grapes", "orange", "papaya", "melon", "mango"]
print(mylist[2:])

#This will return the items from index 2 to the end.

#Remember that index 0 is the first item, and index 2 is the third

Output :-

['grapes', 'orange', 'papaya', 'melon', 'mango']

You can also search for these topics, python range of indexes, start and end of the range index, new list in range of indexes, Example for python range of indexes.

Change List Item Value

Modify a specific item's index number to change the value of a certain item's value :

Example :- Change the third item :

mylist = ["London", "Paris", "Berlin"]
mylist[2] = "Tokyo"

print(mylist)

Output :-

['London', 'Paris', 'Tokyo']

You can also search for these topics, python replace list item by value, how to change value of item in list python, change list item value python condition, Example for chenge the list of items.

Change a Range of Item Values

To modify the value of items inside a certain range, construct a list with the new values and refer to the range of index numbers where you wish to insert the new values :

Example 1 :- modify the values "orange" and "mango" with the values "banana" and "grapes" :

mylist = ["apple", "orange", "mango"]

mylist[1:3] = ["banana", "grapes"]

print(mylist)

Output :-

['apple', 'banana', 'grapes']

If you input more items than you replace, the new items will be placed where you stated, and the leftover items will be moved accordingly :

Example 2 :- It is possible to change the second value by replacing two new ones :

mylist = ["London", "Paris", "Berlin"]

mylist[1:2] = ["New York", "Sydny"]

print(mylist)

Output :-

['London', 'New York', 'Sydny', 'Berlin']

Note :- When the number of things introduced does not equal the number of items replaced, the length of the list will change.

As long as you don't replace more than you add, the new items will be placed where you requested, and the other items will be moved accordingly.

Example 3 :- As a result, the second and third values have been changed to a single value :

mylist = ["London", "Paris", "Berlin"]

mylist[1:3] = ["New York"]

print(mylist)

Output :-

['London', 'New York']

You can also search for these topics, python change range item values generator, change range item values python not working, change range item values python example, list the range of item values.


Python - Add List Items

Python has several methods to add new items to a list.

You can also search for these topics, python add list item together, python create list add item, python add item to beginners of list, fastest way to add item to list python, which function allows a user to add another item to a list in python, Example for python add list items.

Append Items

Use the append() method to add an item to the end of the list.

Example :- The append() method is used to append an item to the list :

mylist = ["London", "Paris", "Berlin"]

mylist.append("Singapore")

print(mylist)

Output :-

['London', 'Paris', 'Berlin', 'Singapore']

You can also search for these topics, python append item to start of list, how to append an item to a list in python, append multiple items python list, python append item to empty list, append items python how it works, how to execute the append() method.

Insert Items

The insert() method can be used to add a new list item without altering any of the existing values.

When you call the method insert(), it will insert a new item at the given index :

Example :- Insert "New York" as the third item:

mylist = ["London", "Paris", "Berlin"]

mylist.insert(2, "New York")

print(mylist)

Output :-

['London', 'Paris', 'New York', 'Berlin']

Note: Like a outcome of the preceding example, the list now contains four items.

You can also search for these topics, python insert item into sorted list, how to insert item in list python, python insert item at end of list, python insert item front of list, insert item python how remove, Example for python insert items.

Extend List

Use the extend() method to append elements from another list to the current one.

Example :- Add the elements of mylist2 to mylist :

mylist = ["London", "Paris", "Berlin"]
mylist2 = ["Singapore", "Malasiya"]

mylist.extend(mylist2)

print(mylist)

Output :-

['London', 'Paris', 'Berlin', 'Singapore', 'Malasiya']

The elements will be placed at the end of the list.

You can also search for these topics, python extend list class, what does list extend do in python, what is difference between append and extend in python list, how to extend empty list in python, python extend list to length, Example for python to extend the list, extend() method using python.

Add Any Iterable

Any iterable object can be added using the extend() method, not append lists (tuples, sets, dictionaries etc.).

Example :- Add elements of a tuple to a list :

mylist = ["London", "Paris", "Berlin"]
mytuple = ("Singapore", "Malasiya")

mylist.extend(mytuple)

print(mylist)

Output :-

['London', 'Paris', 'Berlin', 'Singapore', 'Malasiya']

You can also search for these topics, python add any iterable pattern, python add any iterable example, what is an iterable in python, add any iterable python list, add any iterable python meaning, Example for add any iterable using python.

Remove Specified List Item

The remove() method is used to remove the given list item object from the list.

Example :- Remove a list item contains "Berlin" object :

mylist = ["London", "Paris", "Berlin"]
mylist.remove("Berlin")
print(mylist)

Output :-

['London', 'Paris']

You can also search for these topics, python list remove specified element, python remove list specified item without error, write a python program to remove the first item from a specified list, remove list specified item python by condition, Example for removing specified items.

Remove Specified Index

The pop() method removes the provided index item from the list.

Example 1 :- Remove the third item :

mylist = ["London", "Paris", "Berlin"]
mylist.pop(2)
print(mylist)

Output :-

['London', 'Paris']

Note :- The pop() method removes the last item if you don't give the index.

Example 2 :- Remove the last item :

mylist = ["London", "Paris", "Berlin"]
mylist.pop()
print(mylist)

Output :-

['London', 'Paris']

Removes selected index with del keyword :

Example 3 :- Remove the first item :

mylist = ["London", "Paris", "Berlin"]
del mylist[0]
print(mylist)

Output :-

['Paris', 'Berlin']

The del keyword can also be used to remove all items from the list.

Example 4 :- Delete the entire list :

mylist = ["London", "Paris", "Berlin"]
del mylist
print(mylist)

Note :- This will cause an error because you have succsesfully deleted "mylist".

You can also search for these topics, python remove specific index from list, write a program to remove the item from a specified index in a list in python, remove particular index from list python, remove given index from list python, Example for python Remove Specified Index.

Clear the List

The clear() method is used to remove all items from the list, but not list itself.

The list still remains, but it has no content.

Example :-

mylist = ["London", "Paris", "Berlin"]
mylist.clear()
print(mylist)

Output :-

[]

You can also search for these topics, python clear the list from duplicates, python remove list element by value, how to clear the content of a list in python, delete the list python, Example for python Clear the List.

Python - Loop Lists

Loop Through a List

Using a for loop, you may loop through the list elements.

Example :- Print all items in the list, one by one :

mylist = ["London", "Paris", "Berlin"]
for x in mylist:
  print(x)

Output :-

London
Paris
Berlin

You can also search for these topics, python loop through list with range, how to loop through a list of files in python, python loop through list and write to file, python fastest way to loop through list, Example for python Loop Through a List.

Loop Through the Index Numbers

The index number can also be used to loop through the list entries.

In order to generate a proper iterable, you will need to use the range() and len() methods.

Example :- All items can be printed by referring to their corresponding index number :

mylist = ["London", "Paris", "Berlin"]
for i in range(len(mylist)):
  print(mylist[i])

Output :-

London
Paris
Berlin

In the example above, the iterable produced is [0, 1, 2].

You can also search for these topics, python loop through index number factorial, loop through index number python multidimensional, loop with index in python, index number in for loop python, Example for python Loop Through the Index Numbers.

Using a While Loop

Using a while loop, you may loop through the list elements.

To get the length of the list, use the len() function, then begin at 0 and work your way through the entries by referring to their indexes.

Remember to increment the index by one after each iteration.

Example :- Using a while loop to iterate through all the index numbers, print all items :

mylist = ["London", "Paris", "Berlin"]
i = 0
while i < len(mylist):
  print(mylist[i])
  i = i + 1

Output :-

London
Paris
Berlin

You can also search for these topics, python create list using while loop, python list use while loop example, how to use while loop for list in python, can we use while loop in list comprehension, Example for python Using a While Loop.

Looping Using List Comprehension

When looping through lists, List Comprehension provides the shortest syntax :

Example 1 :- A shorthand for a loop that prints out all elements in a list :

mylist = ["London", "Paris", "Berlin"]
[print(x) for x in mylist]

Output :-

London
Paris
Berlin

You can also search for these topics, python loop use list comprehension perfomance, loop use list comprehension python multiple, Example for python Looping Using List Comprehension.

When you wish to construct a new list based on the values of an existing list, list comprehension gives a more concise syntax for the task.

Based on a list of names, you want a new list that only contains name with the letter "n" in their name.

Example 2 :- You will have to build a for statement with a conditional test inside if you don't have list comprehension :

mylist = ["London", "Paris", "Berlin"]
newlist = [x for x in mylist if "a" in x]

print(newlist)

Output :-

['London', 'Berlin']

You can also search for these topics, python list comprehension multiple condition, python list comprehension practice question, python filter vs list comprehension, list comprehension python square, Example for python List Comprehension.

Python - Sort Lists - Ascending or Descending

Python provides sorting in multiple ways. A list can have sorting with any datatypes like string, numbers and booleans.

Sort List Alphanumerically

There is a method on list objects called sort() that defaults to alphanumerically sort the list in ascending order :

Example 1 :- Sort the list of strings alphabetically :

mylist = ["Ford", "BMW", "Toyoto"]

mylist.sort()

print(mylist)

Output :-

['BMW', 'Ford', 'Toyoto']

Example 2 :- Sort the list of numbers in ascending order :

mylist = [100, 50, 65, 82, 23]

mylist.sort()

print(mylist)

Output :-

[23, 50, 65, 82, 100]

You can also search for these topics, python sort list alphanumerically multiple values, how to sort alphanumeric list in python, sort list alphanumerically python example, default value of Sort List Alphanumerically.

Sort Descending

Use the keyword argument reverse = True to sort in descending order :

Example 1 :- Sort the list of strings in descending order :

mylist = ["Ford", "BMW", "Toyoto"]

mylist.sort(reverse = True)

print(mylist)

Output :-

['Toyoto', 'Ford', 'BMW']

Example 2 :- Sort the list of numbers in descending order :

mylist = [100, 50, 65, 82, 23]

mylist.sort(reverse = True)

print(mylist)

Output :-

[100, 82, 65, 50, 23]

You can also search for these topics, python sort list descending with index, python sort datetime descending, descending order in python without sort function, how to sort descending in python, Example for python Sort Descending.

Customize Sort Function

Using the keyword argument key = function, you can also create your own function and customise it.

The function will produce a number that is being used to order the data in list (the lowest number first) :

You can also search for these topics, python list custom sort function, python sort custom key function, custom sort function python multiple values, what is sort function in python, Example for python Customize Sort Function.

Case In-Sensitive Sort

All capital letters are sorted first in the sort() method by default because it is case sensitive.

Example 1 :- As a result of using case sensitive sorting, an unexpected result can occur :

mylist = ["banana", "Orange", "Grapes", "apple"]

mylist.sort()

print(mylist)

Output :-

['Grapes', 'Orange', 'apple', 'banana']

If we want to sort a list, we can take advantage of built-in key functions.

In order to achieve this, use str.lower as the key function to sort the data.

Example 2 :- Use case-insensitive sorting for the list :

mylist = ["banana", "Orange", "Grapes", "apple"]

mylist.sort(key = str.lower)

print(mylist)

Output :-

['apple', 'banana', 'Grapes', 'Orange']

You can also search for these topics, python sort values case insensitive, python sort without case insensitive, case insensitive sort python example, case insensitive python not working, default Case Insensitive Sort in python.

Reverse Order

However, what happens if you want to reverse an alphabetically arranged list?

Using the reverse() method, you can reverse the current sorting order of the elements in the collection.

Example :- Reverse the order of the items in the list :

mylist = ["banana", "Orange", "Kiwi", "cherry"]

mylist.reverse()

print(mylist)

Output :-

['cherry', 'Kiwi', 'Orange', 'banana']

You can also search for these topics, python reverse order range, sort list python reverse order, how to sort a list in reverse order in python, reverse ascending order python, Example for python reverse order.

Copy a List

You can't just do list2 = list1 to copy a list since list2 is only a record to list1, and any changes made to list1 will be reflected in list2.

It is possible to make a copy using the built-in List copy() function.

The copy() method is used to return a copy of list.

Example :-

mylist = ["London", "Paris", "Berlin"]
mylist2 = mylist.copy()
print(mylist2)

Output :-

['London', 'Paris', 'Berlin']

You can also search for these topics, python copy list without changing original, what is true copy of a list in python, how to copy a linked list python, python copy list by value, python copy list except one element, Example for python Copy a List.

Python - Join Lists

Python provides many ays to join or combine two list.

Join Two Lists

Two or more lists can be joined in Python in a variety of ways, including by concatenation.

Using the + operator is one of the simplest ways to do this.

Example 1 :- Join two list :

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2
print(list3)

Output :-

['a', 'b', 'c', 1, 2, 3]

Two lists can also be joined by adding one item at a time, one by one, from list2 into list1.

Example 2 :- Append list2 items one by one into list1

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
  list1.append(x)

print(list1)

Output :-

['a', 'b', 'c', 1, 2, 3]

It's also possible to utilise the extend() method, which adds elements from one collection to another.

Example 3 :- Use the extend() method to add list2 at the end of list1 :

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

Output :-

['a', 'b', 'c', 1, 2, 3]

You can also search for these topics, python join two list element wise, how to join two list in python, python join two list without duplicates, join every two element of list python, Example for python Join Two Lists.