Showing posts with label Python list. Show all posts
Showing posts with label Python list. Show all posts

Wednesday, November 13, 2024

List Comprehension in Python With Examples

List comprehension in Python is a simple way to create a List from an iterable, it consists of an expression, a loop, an iterable that is iterated using the loop and an optional condition enclosed in a bracket.

Syntax of list comprehension in Python is as given below-

other_list = [expression for iterable_items if condition]

Here for loop is used to generate items for the list by iterating the items of the given iterable. Optional condition is used to filter items if required.

The syntax of list comprehension is equivalent to the following traditional way of list creation-

other_list = []
for item in iterable:
 if condition:
  other_list.append(expression_using_item)

List comprehension Python examples

1. A simple example using the for loop with a range function to create a list of numbers with in a given range.

num_list = [num for num in range(1, 5)]
print(num_list) # [1, 2, 3, 4]

2. Creating a list by iterating alphabets of a word in a String.

name = 'Michael'
alphabet_list = [a for a in name]
print(alphabet_list) #['M', 'i', 'c', 'h', 'a', 'e', 'l']

3. Creating list from another list where each element of the list is multiplied by 2.

num_list = [2, 4, 6, 8]

another_list = [num * 2 for num in num_list]
print(another_list) # [4, 8, 12, 16]

4. List comprehension example of list creation using another list where if condition is also used to filter out items.

name_list = ['Michael', 'Jay', 'Jason', 'Ryan']
another_list = [a for a in name_list if len(a) >= 5]
print(another_list) #['Michael', 'Jason']

5. Sum of the items of two lists to create a new list using list comprehension.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]

another_list = [num_list1[i]+num_list2[i] for i in range(len(num_list1))]
print(another_list) #[6, 8, 10, 12]

6. Find common elements between two lists using list comprehension.

num_list1 = [1, 2, 3, 4]
num_list2 = [4, 8, 2, 5]

common_list = [a for a in num_list1 for b in num_list2 if a == b]
print(common_list) # [2, 4]

Which is equivalent to the following code.

common_list = []
for a in num_list1:
    for b in num_list2:
        if a == b:
            common_list.append(a)
print(common_list)

Finding common elements can also be done in the following way-

common_list = [a for a in num_list1 if a in num_list2]
print(common_list)

That's all for this topic List Comprehension in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. List in Python With Examples
  2. Tuple in Python With Examples
  3. Python Conditional Statement - if, elif, else Statements
  4. Python Generator, Generator Expression, Yield Statement
  5. Magic Methods in Python With Examples

You may also like-

  1. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  2. Python Program to Check Armstrong Number
  3. Interface in Python
  4. Accessing Characters in Python String
  5. How LinkedList Class Works Internally in Java
  6. Java StampedLock With Examples
  7. Constructor Chaining in Java
  8. How to Create PDF From XML Using Apache FOP

Sunday, January 29, 2023

Concatenating Lists in Python

In this post we’ll see how to concatenate or join two lists in Python.

1. The best way to join two lists in Python is to use ‘+’ operator.

num_list1 = [1,2,3,4]
num_list2 = [5,6,7]
#concatenating lists using + operator
num_list1 = num_list1 + num_list2
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7]

2. If you are asked to write a program to join two lists in Python without using any inbuilt function or operator then you can use for loop to iterate one of the list and add elements to another list.

num_list1 = [1,2,3,4]
num_list2 = [5,6,7]
# iterate elements of list
for i in num_list2:
    num_list1.append(i)
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7]

3. You can also join two lists using list comprehension in Python. Trick here is to create a list of lists and then flatten it.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]
joined_list = [j for s in (num_list1, num_list2) for j in s]
print('Joined List-', joined_list)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7, 8]

4. For joining two lists you can also use list.extend() method where you can pass another list as argument.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]
num_list1.extend(num_list2)
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7, 8]

5. Using itertools.chain(*iterables) method that make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

This method returns itertools.chain object which is a generator iterator. By passing it to list() type constructor you can get joined list.

import itertools
num_list1 = ['a', 'b', 'c', 'd']
num_list2 = ['e', 'f', 'g', 'h']
joined_list = list(itertools.chain(num_list1, num_list2))

print('Joined List-', joined_list)

Output

Joined List- ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

That's all for this topic Concatenating Lists in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. List in Python With Examples
  2. Named Tuple in Python
  3. Python for Loop With Examples
  4. String Length in Python - len() Function
  5. Keyword Arguments in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. Python Program to Count Occurrences of Each Character in a String
  3. Interface in Python
  4. String Slicing in Python
  5. ArrayList in Java With Examples
  6. final Keyword in Java With Examples
  7. Just In Time Compiler (JIT) in Java
  8. Spring Job Scheduling Using TaskScheduler And @Scheduled Annotation

Thursday, January 19, 2023

List in Python With Examples

List in Python is one of the sequence data type that can store a group of elements. Some of the important points about Python list are-

  1. A list can store elements of different types.
  2. List maintains the insertion order. Elements are inserted sequentially and you can iterate them in the same order.
  3. One of the major difference between list and other data types like string and tuple is that list is mutable. So, it is possible to change content of a list.
  4. Lists can be indexed (both positive and negative) and sliced.

In this article we’ll see some of the features of the Python list, methods of the list and functions that can be used with List with examples.


Creating a list in Python

In Python list is created by grouping elements with in square brackets [], where the elements are separated by comma.

1. A list of integers.

numbers = [1, 3, 5, 7]
print(numbers) # [1, 3, 5, 7]

2. Creating empty list in Python.

alist = []
print(alist) # []

3. List with element of different types.

alist = [12, 'Sheldon', 'M', 9.99, 9.98]
print(alist)
print(type(alist[0]))
print(type(alist[1]))
print(type(alist[3]))

Output

[12, 'Sheldon', 'M', 9.99, 9.98]
<class 'int'>
<class 'str'>
<class 'float'>

As you can see type of the element at the 0th index is int, type of the element at the 1st index is str where as type of the element at the 3rd index is float.

4. Creating list using type constructor- list()

By passing an iterable in the type constructor list() you can create a list. If no argument is given, the constructor creates a new empty list, [].

alist = list((1,2,3,4))
print(alist) #[1, 2, 3, 4]
alist = list('abcd')
print(alist) #['a', 'b', 'c', 'd']
alist = list(range(1, 9, 2))
print(alist) #[1, 3, 5, 7]

5. Creating a nested list.

You can create a list with in another list (nested list) by grouping elements enclosed in a square bracket with in a square bracket.

alist = [1, 2, [3, 4], 5, 6]
print(alist) #[1, 2, [3, 4], 5, 6]

Refer this post List Comprehension in Python With Examples to see an elegant way to create a list using list comprehension.

Accessing Python List elements using index

List in python uses index starting from 0 to (list_length-1), it also uses negative indexing which starts at -1 from the end (right most element) and goes till list_length.

Here is an example showing list indexing for the stored elements.

Python List index

To access an element you can pass the index in the square brackets. For example to access the 5th element in a list you will pass list[4], as index starts from 0.

alist = [2, 3, 6, 7, 9]
#1st element
print(alist[0])
#last element
print(alist[4])
#last element
print(alist[-1])
#first element
print(alist[-5])

Output

2
9
9
2

Trying to pass index beyond the index range of the list results in ‘index error’. For example here is a list having 5 elements so index range for the list is 0..4, trying to access index 5 results in an error.

alist = [2, 3, 6, 7, 9]
print(alist[5])

Output

    print(alist[5])
IndexError: list index out of range

Slicing a list in Python

Just like string slicing in Python you can do list slicing too which returns a new list.

Format of List slicing is as follows-

Listname[start_position: end_position: increment_step]
  • start_position is the index from which the slicing starts, start_position is included.
  • end_position is the index at which the list slicing ends, end_position is excluded.
  • increment_step indicates the step size. For example if step is given as 2 then every alternate element from start_position is accessed.

All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at list_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.

alist = [2, 4, 6, 8, 10]
print(alist[1:len(alist):2]) #[4, 8]

In the example start_position is 1, end_position is 5 and increment_step is 2 thus the elements at indices 1 and 3 are sliced to create another list.

alist = [2, 4, 6, 8, 10]
print(alist[::])#[2, 4, 6, 8, 10]
print(alist[-3:])#[6, 8, 10]

Iterating all elements of a list using for or while loop

1. Using for loop

alist = [2, 4, 6, 8, 10]
for i in alist:
  print(i)

Output

2
4
6
8
10

As you can see from the output insertion order is maintained in the list.

2. Using while loop

alist = [2, 4, 6, 8, 10]
i = 0;
while i < len(alist):
  print(alist[i])
  i += 1

Output

2
4
6
8
10

Adding elements to a list

To add elements to a list you can use one of the following methods-

  • list.append(x)- Add an item to the end of the list.
  • list.insert(i, x)- Insert an item at a given position. The first argument is the index of the element before which to insert.
  • list.extend(iterable)- Extend the list by appending all the items from the iterable.
alist = [2, 4, 6, 8, 10]
# add new element at the end
alist.append(12)
print(alist)
# insert element before index 4
alist.insert(4, 9)
print(alist)
# append elements from another list
alist.extend([14, 16])
print(alist)

Output

[2, 4, 6, 8, 10, 12]
[2, 4, 6, 8, 9, 10, 12]
[2, 4, 6, 8, 9, 10, 12, 14, 16]

Updating elements of a list in Python

Since Python list is mutable so value of the elements in the list can be modified or elements can be deleted.

To update element’s value you need to access that element using indexing or slicing and assign a new value.

alist = [2, 4, 6, 8, 10]
#Updating value of the element at 3rd index
alist[3] = 9
print(alist) #[2, 4, 6, 9, 10]

Using slicing

alist = [2, 4, 6, 8, 10]
#Updating element at 0th and 1st index
alist[0:2] = 1, 2
print(alist) #[1, 2, 6, 8, 10]

Removing element from a Python list

You can remove element from a list using one of the following method.

  • list.remove(x)- Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
  • list.pop([i])- Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. If index is out of range then IndexError is raised.

Python list remove() method example

alist = ['h', 'e', 'l', 'l', 'o']
if 'e' in alist:
  alist.remove('e')
print(alist)

Output

['h', 'l', 'l', 'o']

In the example using membership operator ‘in’ first it is checked whether the element exists in the lists or not, if it does then it is removed using remove() method.

Python list pop() method example

alist = ['h', 'e', 'l', 'l', 'o']
elem = alist.pop(2)
print(elem)

Output

l

That's all for this topic List in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Concatenating Lists in Python
  2. Tuple in Python With Examples
  3. Named Tuple in Python
  4. Python while Loop With Examples
  5. Python Generator, Generator Expression, Yield Statement

You may also like-

  1. Python Conditional Statement - if, elif, else Statements
  2. Operator Overloading in Python
  3. Python Program to Check if Strings Anagram or Not
  4. raise Statement in Python Exception Handling
  5. Java Collections Interview Questions And Answers
  6. Volatile Keyword in Java With Examples
  7. Difference Between throw And throws in Java
  8. Quick Sort Program in Java