Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction🙆
2.
Python Lists📄
2.1.
Here are some examples of python lists:
2.2.
How to create lists in Python?
2.3.
How to access any element of a list in Python?
3.
List Operations🧑‍💻
3.1.
Joining ➕ Lists
3.2.
Replicating👉👈Lists
3.3.
Slicing🔪 the Lists
4.
List Comprehension👀
5.
Frequently Asked Questions
5.1.
What is Python?
5.2.
What are lists?
5.3.
What is List comprehension?
5.4.
What are the common list operations?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Lists and List Comprehension

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction🙆

Python is known for pushing programmers and developers to write code that is efficient, easy to understand, and almost as easy to read. 

Python List and List Comprehension features are two of the language's most distinguishing features, which help us build significant functionality with just one line of code😮. Get your basics about lists in Python clear; this article will help you. Today in this blog, we will discuss lists and list comprehensions in detail.

Python Lists📄

Python Lists are containers that can hold any value. The most important feature of Python Lists is that they are changeable💡, which means you can change the elements of a list while it is still in use.

python lists

When you alter a list's member, Python does not create a new✨ list.

A list is a Python data type that can be used to store a succession of values of any sort. In Python, square brackets[] denote lists.

Here are some examples of python lists:

1. List of numbers

n_list=[12,22,13] #this will create a list of numbers
[12, 22, 13]

 

2. List of Characters

c_list=['c', 'd', 's’] #this will create a list of characters                     
['c', 'd', 's’]  

Also see, Python Operator Precedence

How to create lists in Python?

We can create lists in Python using square brackets. 

Below is an example of it.

newList = [1,2,3,4]
print(newList)

Output

[1,2,3,4]

We can also create a list from existing sequences. We have the list() object using which we can create a list. For example:

L1 = list('Coding Ninjas Studio')
print(L1)

Output

['c', 'o', 'd', 'e', 's', 't', 'u', 'd', 'i', 'o']

Creating list from tuple:

t = ('c', 'o', 'd', 'e')
# Passing tuple t inside the list method
L2 = list(t)         
print("List generated from tuple:", L2)

Output

List generated from tuple: ['c', 'o', 'd', 'e']

How to access any element of a list in Python?

We can simply access the element using its index just as we do in an array. 

For example:

newList = [1,2,3,4]
print(newList[0])

 

Output

1

We also have a concept of negative indexing in lists. If you pass a negative index, Python add the length of the list and then returns the element present at that particular index. Let us understand this through an example:

newList = [1,2,3,4]
print(newList[0])
print(newList[-4])

 

Output

1
1

The negative indexing starts from -1 not from 0. So in the above example newList[-4] is calculated as newList[-4+4] which is newList[0].

You can practice by yourself with the help of online python compiler for better understanding.

So now you have become familiar with lists😎. Let’s look at some list operations now.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

List Operations🧑‍💻

The most frequent operations with lists are joining lists, replicating lists, and slicing lists. We will talk about them in detail now. Also, if you want to learn about list methods, you can refer to this article😎.

list operations

Joining ➕ Lists

Joining, as the name suggests, is used to add two lists. The + operator does the joining of two lists. 

join two lists

Consider the example given below:

L1 = ['C', 'o', 'd', 'e']
L2 = ['S', 't', 'u', 'd', 'i', 'o']

# Joined two lists using the "+" operator
L3 = L1 + L2    
print(L3)

 

Output

['C', 'o', 'd', 'e', 'S', 't', 'u', 'd', 'i', 'o']

 

The + operator adds two lists together to create a new one. The resultant list (L3), as can be seen, includes the initial components from the first list (L1), followed by entries from the second(L2). You may also make a new list by combining two or more listings.

When used with lists, the + operator needs both operands to be of the list type. Otherwise, it will lead to errors❌.

Replicating👉👈Lists

We can replicate lists, i.e., it repeats a list specified number of times and creates a new list. The '*' operator is used for this purpose.

replicating lists

For example:-

L1 = [‘i’, ‘love’,‘coding’]

# The * operator repeats a list specified no. of times and creates a new list
print(L1 * 3)

 

 Output

[‘i’, ‘love’,’coding’, ‘i’, ‘love’,’coding’, ‘i’, ‘love’,’coding’]

Slicing🔪 the Lists

It is used to slice out subparts from the list. There are various🥱 formats in which we can use slicing. 

slicing lists

- The first way to slice a list in Python is:

NEW_LIST = LIST [start : stop]

 

The above statement will create a new ✨ list having elements of list L, in the range of [start, stop] exclusive of the stop.

Consider the following example:

list = [10, 12, 12 , 19]
newList = list[0 : 2]
print(newList)

 

Output

[10, 12]

 

It's worth noting that if the resultant index for regular indexing is outside of the list, Python will throw an IndexError exception 🙂. Slices, on the other hand, are treated as borders in slice operations, and the output contains all elements between the limits. Python returns the elements in a list slice that fall within specified boundaries, if any, for a start and end provided outside list restrictions without generating any exceptions.

 

- The other way of slicing a list is:

NEW_LIST = LIST[start : stop : step]

 

LIST[start : stop: step] creates a sub-list starting from the start index and ending at the stop index(not including it) while skipping a step - 1 element in between.

Consider the following example:

list = [1,3,5,7,9,11,13,15,17,19]
newList = list[0: 10: 2]
print(newList)

 

Output

[1,5,9,13,17]

List Comprehension👀

In Python, list comprehension is a simple and elegant approach to generating a new list💡 from an existing one.

list comprehension

A list comprehension has an expression that is followed by a for statement in square brackets.

Example of creating a list in which the elements stored are increasing power by 3.

newList = [3 ** x for x in range(6)]
print(newList)

 

Output

[3, 9, 27, 81, 243, 729]

 

The above code is a replacement for this code:

newList = []
for x in range(6):
   newList.append(3 ** x)

 

Also, we can use if and else statements inside it. Let's see some examples.

newList = [3 ** x for x in range(6) if x > 4]
print(newList)

 

Output

[243, 729]

 

Must Read Python List Operations

Frequently Asked Questions

What is Python?

Python is a high-level programming language. Its design philosophy prioritizes code readability and makes extensive use of indentation. Its language constructs and object-oriented approach are aimed at assisting programmers in writing clear, logical code for both small and large projects.

What are lists?

A list is a Python data type that can be used to store a succession of values of any sort. In Python, square brackets denote lists. The most important feature of Python Lists is that they are changeable, which means you can change the elements of a list while it is still in use.

What is List comprehension?

In Python, list comprehension is a simple and elegant approach to generating a new list from an existing one. AlA list comprehension consists of an expression followed by a for statement inside square brackets.

What are the common list operations?

The most frequent operations with lists are joining lists, replicating lists, slicing lists, List Membership Tests, Delete List Elements, Accessing elements from the list, and Removing Elements from the list.

Conclusion

We saw and learned about an essential topic in Python, which is Lists. We saw how we could create a new list, saw list operations, and finally talked about list comprehension. This is a start to becoming a star programmer. Python is in demand✨. Learn Python as it is being used in data science, machine learning, artificial intelligence, and deep learning. Thus it’s time to move over to our industry-leading practice platform Coding Ninjas Studio to practice top problemsread interview experiences, and many more. 

Happy Learning!

Next article
Lists Methods
Live masterclass