DEV Community

Sowntharya
Sowntharya

Posted on

Python Lists for Beginners

1. What is a List in Python?
A list is a built-in data type in Python that allows us to store multiple values in a single variable.

Instead of creating separate variables for every value, we can store all values together in a list.

Example:

student1 = "Prem"
student2 = "Ragul"
student3 = "Sam"
Enter fullscreen mode Exit fullscreen mode

Instead, we can create a single list:

students = ["Prem", "Ragul", "Sam"]
print(students)  //['Prem', 'Ragul', 'Sam']
Enter fullscreen mode Exit fullscreen mode

Important characteristics of lists
Ordered: Elements maintain their insertion order.
Mutable: We can modify elements after creating a list.
Allows duplicates: The same value can appear multiple times.
Different data types:A list can contain integers, strings, floats, and other data types.
Indexed: Every element has an index starting from 0.

Example for data type :

my_list = [10, "Python", 20.5, True, 10]
print(my_list)  //[10, 'Python', 20.5, True, 10]
Enter fullscreen mode Exit fullscreen mode

2. Different ways to create a list
There are several ways to create a list in Python.

Method 1: Using square brackets

l = [10, 20, 30, 40]
print(l)
Enter fullscreen mode Exit fullscreen mode

Method 2: Creating an empty list

l = []
print(l)        //[]
print(type(l))  //<class 'list'>
Enter fullscreen mode Exit fullscreen mode

Method 3: Using the list() constructor

l = list((10, 20, 30))
print(l)      //[10, 20, 30]
Enter fullscreen mode Exit fullscreen mode

Method 4: Using range()
The range() function generates a sequence of numbers.

l = range(1, 10, 2)
print(l)  //range(1, 10, 2)
Enter fullscreen mode Exit fullscreen mode

To convert it into a list:

l = list(range(1, 10, 2))
print(l)  //[1, 3, 5, 7, 9]
Enter fullscreen mode Exit fullscreen mode

syntax : range(start, stop, step)
Start: Starting number.
Stop: Ending limit (excluded).
Step: Difference between numbers.

Example 1: Basic input

name = input("What is your name? ")
print("Hello", name)
Enter fullscreen mode Exit fullscreen mode

Example 2: Adding two numbers

no1 = input("Enter first number: ")
no2 = input("Enter second number: ")

print(no1 + no2)  // 2+2 = 22 only concat the value
Enter fullscreen mode Exit fullscreen mode

Why?

Because input() returns strings, Python joins the two strings instead of performing mathematical addition.

Example 3: Converting input into integers

python

no1 = int(input("Enter first number: "))
no2 = int(input("Enter second number: "))

print(no1 + no2) // 20+20 = 40
Enter fullscreen mode Exit fullscreen mode
no1 = input("Enter first number: ")
no2 = input("Enter second number: ")

print(int(no1) + int(no2))
Enter fullscreen mode Exit fullscreen mode

Other commonly used conversions include:
int() – Converts to an integer.
float() – Converts to a floating-point number.
str() – Converts to a string.
list() – Converts an iterable into a list.

Example 4: Taking a list as input

grocery_list = eval(input("Enter list of items: "))
print(grocery_list)
Enter fullscreen mode Exit fullscreen mode

["Rice", "Milk", "Sugar"]
Output: ['Rice', 'Milk', 'Sugar']

Important: Avoid using eval() with user input because it can execute arbitrary Python code. A safer alternative for entering a Python-style list is ast.literal_eval().

import ast

grocery_list = ast.literal_eval(input("Enter list: "))
print(grocery_list)
Enter fullscreen mode Exit fullscreen mode

4. Accessing list elements (Indexing)

  • Each element in a list has an index.
  • Python supports positive and negative indexing.

Example :

l = ["abcd", "efgh", "xyz", "sam"]

print(l[0])   # abcd
print(l[1])   # efgh
print(l[-1])  # sam
print(l[-2])  # xyz
Enter fullscreen mode Exit fullscreen mode

5. List slicing
Slicing is used to access a particular portion of a list.

Syntax: list[start:stop:step]

Example:

l = [10, 20, 30, 40, 50]

print(l[1:4])
print(l[:3])
print(l[2:])
print(l[::-1])
Enter fullscreen mode Exit fullscreen mode

Output:
[20, 30, 40]
[10, 20, 30]
[30, 40, 50]
[50, 40, 30, 20, 10]
Remember: The stop index is excluded.

6. Adding elements to a list
Python provides different methods to add elements to a list.

A. append()
The append() method adds an element at the end of the list.
syntax : list.append(element)

Example:

l = []
l.append("abcd")
l.append("efgh")
l.append("xyz")
l.append("abcd")

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: ['abcd', 'efgh', 'xyz', 'abcd']

Important points:

  • Adds only one element at a time.
  • Always adds the element at the end.
  • Allows duplicate values.
  • Modifies the original list.

B. insert()
The insert() method adds an element at a specific index.
syntax : list.insert(index, element)

Example:

l = ["abcd", "efgh", "xyz"]
l.insert(2, "sowntharya")

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: ['abcd', 'efgh', 'sowntharya', 'xyz']

l.insert(0, "prem")
Enter fullscreen mode Exit fullscreen mode

Adds the element at the beginning.

l.insert(-1, "yyy")
Enter fullscreen mode Exit fullscreen mode

Adds the element before the last element.

l.insert(100, "sam")
Enter fullscreen mode Exit fullscreen mode

Adds the element at the end because the index is beyond the list's length.

Important: insert() requires two arguments: index and value.

Difference between append() and insert()

  • append() - Adds at the end, Takes one argument, l.append(10)

  • insert() - Adds at a specified index, Takes two arguments, l.insert(0, 10)

7. Removing elements from a list
Python provides multiple methods to remove elements.

A. remove()
Removes the first occurrence of a specified value.

l = ["abcd", "efgh", "xyz", "abcd"]
l.remove("xyz")

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: ['abcd', 'efgh', 'abcd']
Note: If the value does not exist, Python raises a ValueError.

B. pop()
Removes an element using its index and returns the removed element.

l = [10, 20, 30, 40]
l.pop()

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: [10, 20, 30]
We can also specify an index:

l.pop(1)
print(l)
Enter fullscreen mode Exit fullscreen mode

Output: [10, 30]

C. clear()
Removes all elements from the list.

l = [10, 20, 30]
l.clear()

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: []

8. Modifying list elements
Lists are mutable, meaning we can change their values after creating them.
Modifying using an index.

l = ["abcd", "efgh", "xyz"]
l[0] = "prem"

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: ['prem', 'efgh', 'xyz']

Modifying using slicing

l = ["abcd", "efgh", "xyz"]
l[1:3] = ["ragul"]

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: ['abcd', 'ragul']
Here, two elements are replaced with one element.

9. Important built-in list methods
Here are some useful list methods to remember.

Method ** **Description
append() - Adds an element at the end
insert() - Adds an element at a specified position
extend() - Adds multiple elements from an iterable
remove() - Removes the first matching value
pop() - Removes and returns an element
clear() - Removes all elements
index() - Returns the index of a value
count() - Counts occurrences of a value
sort() - Sorts the list
reverse() - Reverses the list
copy() - Creates a shallow copy

A few more examples
1. extend()

l = [10, 20]
l.extend([30, 40])

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: [10, 20, 30, 40]
Difference between append and extend:

l = [10, 20]
l.append([30, 40])

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: [10, 20, [30, 40]]
append() adds the entire list as one element, whereas **extend() **adds its individual elements.

2. count()
Counts how many times an element appears.

l = ["abcd", "efgh", "abcd", "xyz"]

print(l.count("abcd"))
Enter fullscreen mode Exit fullscreen mode

Output: 2

3. index()
Returns the index of the first occurrence of a value.

l = ["abcd", "efgh", "xyz"]

print(l.index("xyz"))
Enter fullscreen mode Exit fullscreen mode

Output: 2
If the value doesn't exist, it raises a ValueError.

4. sort()
Sorts the elements in ascending order by default.

l = [40, 10, 30, 20]
l.sort()

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: [10, 20, 30, 40]

For descending order:

l.sort(reverse=True)
Enter fullscreen mode Exit fullscreen mode

5. reverse()
Reverses the order of elements.

l = [10, 20, 30, 40]
l.reverse()

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: [40, 30, 20, 10]

6. copy()

Creates a shallow copy of a list.
l1 = [10, 20, 30]
l2 = l1.copy()

print(l2)
Enter fullscreen mode Exit fullscreen mode

10. Using loops with lists

  • We can use loops to access and modify list elements.
  • This is similar to the example you practised today.

Example: Replace xyz with ragul

l = ["abcd", "efgh", "xyz", "abcd"]

for i in range(len(l)):
    if l[i] == "xyz":
        l[i] = "ragul"

print(l)
Enter fullscreen mode Exit fullscreen mode

Output: ['abcd', 'efgh', 'ragul', 'abcd']

How does this work?
len(l) returns the number of elements in the list.
range(len(l)) generates the index positions.
l[i] accesses the element at the current index.
The if condition checks whether the element is equal to "xyz".
If the condition is true, the element is replaced with "ragul".

You can also use a simpler approach:

l = ["abcd", "efgh", "xyz", "abcd"]

for i in l:
    print(i)
Enter fullscreen mode Exit fullscreen mode

This directly accesses the elements without using their indexes.

Today, I learned about Python lists and their important features. Lists help us store multiple values in a single variable. They are ordered, mutable, and allow duplicate elements.

I also learned how to create lists, take user input, access elements using indexing and slicing, add elements using append() and insert(), remove elements, modify values, and use loops to work with lists.

Top comments (0)