- Python Lists Example
- what is list in python?
- How to create a list?
- python create empty list
- python create list with numbers
- python create list of string numbers
- How to access elements from a list?
- python access list element by index
- python access list element by negative index
- python list get element by index range
- Python find the length of list
- Add item to list python
- Add item to list at specific index python
- Remove item from list python
- python remove specific item from list
- python copy list of lists
- python join two lists
- Lists Methods Python
- Author Admin
- Python List
- Create a List
- Access List Elements
- Negative Indexing in Python
- Slicing of a List
- Add Elements to a List
- Change List Items
- Remove an Item From a List
- List Methods
- Iterating through a List
- Check if an Element Exists in a List
- List Length
- List Comprehension
- Table of Contents
- Video: Python Lists and Tuples
Python Lists Example
In this post, you will learn what is Python lists, how to create a list, how to adding or removing elements from python lists and so on.
Simultaneously tell you. Which type of in-build python methods use with python list. In-build methods are also included with the example. Which will make you easier to understand.
what is list in python?
The lists in python are Collections of items. which is ordered and changeable. The lists are defined by having values between square brackets [ ].
How to create a list?
To create a list in Python, place all the items within [] brackets and separate the items with commas.
A Python list can contain elements of different data types. Such as integer, float, string, etc.
python create empty list
First of all, we will create an empty list in python:
python create list with numbers
Now we will create a list in Python, in which list will be Numbers:
# list of integers my_list = [1, 2, 3]
python create list of string numbers
Now we will create another list which will contain numbers, strings, etc:
# list with mixed datatypes my_list = [1, "Hello", 3.4]
How to access elements from a list?
We learned how to create lists in Python with different data types.
Now we will learn how to access items / elements from lists.
python access list element by index
# list of integers my_list = [10, 20, 30] print(my_list[1])
As there is a list, from this list we have access to the items according to the index.
python access list element by negative index
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.
# list of integers my_list = [10, 20, 30] print(my_list[-1])
python list get element by index range
You can get items in the range from the list. For this, the start and end range values have to be passed:
# list of integers my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90] print(my_list[2:6])
Python find the length of list
If you want to find/get the list’s length, then you have to use the Python len() function.
You can see the below example how the list is find by length:
# list of integers my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90] print(len(my_list))
Add item to list python
Here you will learn how to add items to the list in Python.
The append () function is used to add items to the Python list. And the item is added to the end of the list.
# list of integers my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90] my_list.append(100) print(my_list)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Add item to list at specific index python
If you want to add an item to the specific index of the list in Python, then you have to use insert() for it.
# list of integers my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90] my_list.insert(1, 5) print(my_list)
[10, 5, 20, 30, 40, 50, 60, 70, 80, 90]
Remove item from list python
By now you have learned how to add and access items in the list. Now you will learn how to delete/remove items from the Python list.
The remove() method is used to remove the first occurrence item with a specified value on python lists.
To delete/remove items from the Python list, use the function remove() of Python.
You can see the example below. How to remove/delete items from the list:
# list of integers my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90] my_list.remove(90) print(my_list)
python remove specific item from list
If you want to remove a specific item from the list of Python list. So for this you have to use pop () function.
You can see the example below. Let’s use the Python pop() function to remove the item from the specific index:
# list of integers my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90] my_list.pop(2) print(my_list)
Note:- If you do not pass the index inside the pop() function, it will remove the value of last indexes in the python list.
If you want to remove items from the specific index of Python list, you can also use del keyword for this
Let’s take an example to understand better how to use the del keyword and remove the item from the list:
# list of integers my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90] del my_list[3] print(my_list)
In the example given, we have removed the item that was on the 3rd index in python lists. You can see the output below:
python copy list of lists
In Python, you want to copy one list to another list. So for this, you have to use the copy () function of Python.
The copy () function copies one list into another list.
# list of integers my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90] blist= my_list.copy() print(blist)
[10, 20, 30, 40, 50, 60, 70, 80, 90]
python join two lists
If you want to join two lists in Python. So you can use its + operator. This will join your two lists.
Now we take an example. In this example, two lists are taken, one is a list of string data types and the other is a list of integer data types. We will use the + operator to connect to it:
list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3)
Lists Methods Python
Author Admin
My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.
Python List
In Python, lists are used to store multiple data at once.
Suppose we need to record the ages of 5 students. Instead of creating 5 separate variables, we can simply create a list.
Create a List
We create a list by placing elements inside [] , separated by commas. For example,
ages = [19, 26, 23] print(ages) # Output: [19, 26, 23]
Here, we have created a list named ages with 3 integer items.
# list with elements of different data types list1 = [1, "Hello", 3.4] # list with duplicate elements list1 = [1, "Hello", 3.4, "Hello", 1] # empty list list3 = []
Note: We can also create a list using the list() constructor.
Access List Elements
In Python, lists are ordered and each item in a list is associated with a number. The number is known as a list index.
The index of the first element is 0, second element is 1 and so on. For example,
languages = ["Python", "Swift", "C++"] # access item at index 0 print(languages[0]) # Python # access item at index 2 print(languages[2]) # C++
In the above example, we have created a list named languages .
Here, we can see each list item is associated with the index number. And we have used the index number to access the items.
Remember: The list index always starts with 0. Hence, the first element of a list is present at index 0, not 1.
Negative Indexing in Python
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
languages = ["Python", "Swift", "C++"] # access item at index 0 print(languages[-1]) # C++ # access item at index 2 print(languages[-3]) # Python
Note: If the specified index does not exist in a list, Python throws the IndexError exception.
Slicing of a List
In Python, it is possible to access a portion of a list using the slicing operator : . For example,
# List slicing in Python my_list = ['p','r','o','g','r','a','m','i','z'] # items from index 2 to index 4 print(my_list[2:5]) # items from index 5 to end print(my_list[5:]) # items beginning to end print(my_list[:])
['o', 'g', 'r'] ['a', 'm', 'i', 'z'] ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
- my_list[2:5] returns a list with items from index 2 to index 4.
- my_list[5:] returns a list with items from index 5 to the end.
- my_list[:] returns all list items
Note: When we slice lists, the start index is inclusive, but the end index is exclusive.
Add Elements to a List
Lists are mutable (changeable). Meaning we can add and remove elements from a list.
Python list provides different methods to add items to a list.
1. Using append()
The append() method adds an item at the end of the list. For example,
numbers = [21, 34, 54, 12] print("Before Append:", numbers) # using append method numbers.append(32) print("After Append:", numbers)
Before Append: [21, 34, 54, 12] After Append: [21, 34, 54, 12, 32]
In the above example, we have created a list named numbers . Notice the line
Here, append() adds 32 at the end of the array.
2. Using extend()
We use the extend() method to add all the items of an iterable (list, tuple, string, dictionary, etc.) to the end of the list. For example,
numbers = [1, 3, 5] even_numbers = [4, 6, 8] # add elements of even_numbers to the numbers list numbers.extend(even_numbers) print("List after append:", numbers)
List after append: [1, 3, 5, 4, 6, 8]
Here, numbers.extend(even_numbers) adds all the elements of even_numbers to the numbers list.
3. Using insert()
We use the insert() method to add an element at the specified index.
numbers = [10, 30, 40] # insert an element at index 1 (second position) numbers.insert(1, 20) print(numbers) # [10, 20, 30, 40]
Change List Items
Python lists are mutable. Meaning lists are changeable. And we can change items of a list by assigning new values using the = operator. For example,
languages = ['Python', 'Swift', 'C++'] # changing the third item to 'C' languages[2] = 'C' print(languages) # ['Python', 'Swift', 'C']
Here, initially the value at index 3 is ‘C++’ . We then changed the value to ‘C’ using
Remove an Item From a List
1. Using del Statement
In Python we can use the del statement to remove one or more items from a list. For example,
languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R'] # deleting the second item del languages[1] print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust', 'R'] # deleting the last item del languages[-1] print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust'] # delete the first two items del languages[0 : 2] # ['C', 'Java', 'Rust'] print(languages)
2. Using remove()
We can also use the remove() method to delete a list item. For example,
languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R'] # remove 'Python' from the list languages.remove('Python') print(languages) # ['Swift', 'C++', 'C', 'Java', 'Rust', 'R']
Here, languages.remove(‘Python’) removes ‘Python’ from the languages list.
List Methods
Python has many useful list methods that makes it really easy to work with lists.
Method | Description |
---|---|
append() | add an item to the end of the list |
extend() | add all the items of an iterable to the end of the list |
insert() | inserts an item at the specified index |
remove() | removes item present at the given index |
pop() | returns and removes item present at the given index |
clear() | removes all items from the list |
index() | returns the index of the first matched item |
count() | returns the count of the specified item in the list |
sort() | sort the list in ascending/descending order |
reverse() | reverses the item of the list |
copy() | returns the shallow copy of the list |
Iterating through a List
We can use a for loop to iterate over the elements of a list. For example,
languages = ['Python', 'Swift', 'C++'] # iterating through the list for language in languages: print(language)
Check if an Element Exists in a List
We use the in keyword to check if an item exists in the list or not. For example,
languages = ['Python', 'Swift', 'C++'] print('C' in languages) # False print('Python' in languages) # True
- ‘C’ is not present in languages , ‘C’ in languages evaluates to False .
- ‘Python’ is present in languages , ‘Python’ in languages evaluates to True .
List Length
We use the len() function to find the size of a list. For example,
languages = ['Python', 'Swift', 'C++'] print("List: ", languages) print("Total Elements: ", len(languages)) # 3
List: ['Python', 'Swift', 'C++'] Total Elements: 3
List Comprehension
List comprehension is a concise and elegant way to create lists. For example,
# create a list with value n ** 2 where n is a number from 1 to 5 numbers = [n**2 for n in range(1, 6)] print(numbers) # Output: [1, 4, 9, 16, 25]
numbers = [n**2 for n in range(1, 6)]
numbers = [] for n in range(1, 6): numbers.append(n**2)
Table of Contents
- Introduction
- Create a Python List
- Access List Elements
- Negative Indexing in Python
- Slicing of a List
- Add Elements to a List
- Change List Items
- Remove an Item From a List
- List Methods
- Iterating through a List
- Check if an Item Exists
- Python List Length