1. Three Ways to Create a List in Python
In Python, we can create a list in three different ways.
Method 1: Using Empty Square Brackets []
We can create an empty list using square brackets.
l = []
print(l)
print(type(l))
Output:
[]
<class 'list'>
Here:
- [] creates an empty list.
- The data type is list.
- We can add elements later using list methods like append() and insert().
Method 2: Using list() with range()
The range() function generates a sequence of numbers.
To convert that sequence into a list, we use the list() function.
l = list(range(1, 10, 2))
print(l)
Output:
[1, 3, 5, 7, 9]
Let's understand the arguments:
range(1, 10, 2)
- 1 – Starting value.
- 10 – Ending value (excluded).
- 2 – Step value (increment by 2).
Remember:
range() generates a sequence of numbers, whereas list() converts that sequence into a list.
Method 3: Using eval(input())
We can also create a list by getting input from the user.
l = eval(input("Enter list: "))
print(l)
print(type(l))
Input:
[10, 20, 30, 40]
Output:
[10, 20, 30, 40]
<class 'list'>
Let's understand how it works:
- input() receives the user's input as a string.
- eval() evaluates the entered string as a Python expression.
- The result is stored in the variable l.
2. Understanding range() in Python
The range() function is used to generate a sequence of numbers.
Syntax:
range(start, stop, step)
Example:
l = range(1, 10, 2)
print(l)
Output:
range(1, 10, 2)
It displays a range object instead of directly displaying all the numbers.
3. Taking User Input in Python
The input() function is used to get information from the user while a program is running.
Without a message
name = input()
print("Hello", name)
Output:
Vasanth
Hello Vasanth
With a message
name = input("What is your name? ")
print("Welcome", name)
Output:
What is your name? Vasanth
Welcome Vasanth
The message inside input() is displayed before accepting the user's input.
What is the return data type of input()?
The return data type of input() is always String (str).
Even if the user enters a number, Python considers it a string.
4. Understanding String Concatenation
Let's see what happens when we perform addition using user input.
no1 = input("Enter number: ")
no2 = input("Enter number: ")
print(no1 + no2)
Input:
10
20
Output:
1020
Why?
Because input() returns strings, Python joins the two strings instead of performing mathematical addition.
5. Type Conversion Using int()
If we want to perform mathematical calculations with user input, we need to convert the string into an integer.
We can use the int() function.
no1 = int(input("Enter number: "))
no2 = int(input("Enter number: "))
print(no1 + no2)
Input:
10
20
Output:
30
Here is what happens:
- input() receives the value as a string.
- int() converts the string into an integer.
- The + operator performs mathematical addition.
Note: If the user enters something that cannot be converted into an integer, Python raises a ValueError.
6. Understanding Lists in Python
A list is a collection of elements stored in a single variable.
Lists have the following characteristics:
- Ordered: Elements maintain their insertion order.
- Mutable: We can modify existing elements.
- Duplicates allowed: The same value can appear multiple times.
- Different data types: A list can store integers, strings, floats, and other objects.
Example:
l = [10, "Python", 20.5, "Java"]
print(l)
Output:
[10, 'Python', 20.5, 'Java']
7. Adding Elements Using append()
The append() method adds a new element at the end of a list.
Example:
l = []
l.append("abcd")
l.append("pqrs")
l.append("xyz")
l.append("abcd")
print(l)
Output:
['abcd', 'pqrs', 'xyz', 'abcd']
Notice that abcd appears twice.
Python lists allow duplicate values.
Important: append() always adds the element at the end of the list.
8. Finding the Length Using len()
The len() function returns the total number of elements in a list.
l = ["abcd", "pqrs", "xyz", "abcd"]
print(len(l))
Output:
4
9. Counting Duplicate Values Using count()
The count() method tells us how many times a particular element appears in a list.
l = ["abcd", "pqrs", "xyz", "abcd"]
print(l.count("abcd"))
Output:
2
Because abcd appears two times in the list.
10. Finding an Element's Position Using index()
The index() method returns the position of the first occurrence of an element.
l = ["abcd", "pqrs", "xyz", "abcd"]
print(l.index("abcd"))
print(l.index("xyz"))
Output:
0
2
Remember: List indexing starts from 0, not 1.
If the specified element does not exist, Python raises a ValueError.
11. Removing Elements Using remove()
The remove() method removes the first matching element from a list.
l = []
l.append("abcd")
l.append("pqrs")
l.append("xyz")
l.append("abcd")
l.remove("xyz")
print(l)
Output:
['abcd', 'pqrs', 'abcd']
Here, xyz is removed from the list.
12. Inserting Elements Using insert()
The insert() method adds an element at a particular position in a list.
Syntax:
list.insert(index, element)
Example:
l = ["abcd", "pqrs", "xyz", "abcd"]
l.insert(2, "ghi")
print(l)
Output:
['abcd', 'pqrs', 'ghi', 'xyz', 'abcd']
The new element ghi is inserted at index 2.
Understanding Positive and Negative Indexing
l = ["abcd", "pqrs", "xyz", "abcd"]
l.insert(-1, "yyy")
print(l)
Output:
['abcd', 'pqrs', 'xyz', 'yyy', 'abcd']
Negative indexing counts positions from the end of the list.
Here, -1 inserts the new element before the last element.
What happens if we insert at an index beyond the list length?
l = ["abcd", "pqrs", "xyz"]
l.insert(100, "bbb")
print(l)
Output:
['abcd', 'pqrs', 'xyz', 'bbb']
Python inserts the element at the end if the index is greater than the list length.
13. Difference Between append() and insert()
Both append() and insert() are used to add elements to a list, but they work differently.
| Feature | append() | insert() |
|---|---|---|
| Purpose | Adds an element at the end | Adds an element at a specific position |
| Arguments | One argument | Two arguments |
| Position | Always the end | Specified index |
| Syntax | l.append(value) |
l.insert(index, value) |
Example using append()
l = [10, 20, 30]
l.append(40)
print(l)
Output:
[10, 20, 30, 40]
The element 40 is added at the end.
Example using insert()
l = [10, 20, 30]
l.insert(1, 40)
print(l)
Output:
[10, 40, 20, 30]
The element 40 is added at index 1.
Easy way to remember:
- append() → Add at the end.
- insert() → Add wherever you want.
14. Updating List Elements Using Indexing
Lists are mutable, which means we can change their existing elements.
Let's take an example.
l = []
l.append("abcd")
l.append("pqrs")
l.append("xyz")
l.append("abcd")
for i in range(len(l)):
if l[i] == "pqrs":
l[i] = "ragul"
print(l)
Output:
['abcd', 'ragul', 'xyz', 'abcd']
Let's understand the logic:
- len(l) returns the total number of elements.
- range(len(l)) generates index positions.
- l[i] accesses each element using its index.
- The if condition checks whether the current element is pqrs.
- If the condition is true, the element is replaced with ragul.
This is how we can update a particular element inside a list.
Top comments (0)