0% found this document useful (0 votes)
5 views5 pages

Python List Tutorial

This document is a comprehensive guide to Python's list data type, detailing its properties, methods, and common usage patterns. It covers topics such as creating lists, indexing, slicing, list methods, built-in functions, operators, list comprehensions, and copying lists. Additionally, it includes tips for handling nested lists and common pitfalls to avoid during interviews.

Uploaded by

arsalanakram246
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Python List Tutorial

This document is a comprehensive guide to Python's list data type, detailing its properties, methods, and common usage patterns. It covers topics such as creating lists, indexing, slicing, list methods, built-in functions, operators, list comprehensions, and copying lists. Additionally, it includes tips for handling nested lists and common pitfalls to avoid during interviews.

Uploaded by

arsalanakram246
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Lists — Complete Tutorial

A comprehensive guide to Python's list data type, covering all built-in methods, operators, functions, and common patterns with examples.

Contents
1. Introduction to Lists
2. Creating Lists
3. Indexing and Slicing
4. List Methods (all 11, official)
5. Built-in Functions that Work with Lists
6. Operators on Lists
7. List Comprehensions
8. Copying Lists (shallow vs deep)
9. Nested Lists / 2D Lists
10. Common Patterns and Interview Tips

1. Introduction to Lists

A list is an ordered, mutable (changeable) collection of items in Python. Lists can hold items of different data types, allow duplicate values, and are
defined using square brackets [] .

fruits = ["apple", "banana", "cherry"]


mixed = [1, "hello", 3.14, True]

Key properties:

Property Description

Ordered Items maintain the order in which they were inserted

Mutable Elements can be added, removed, or changed after creation

Allows duplicates Same value can appear multiple times

Heterogeneous Can store mixed data types in a single list

Indexed Elements accessed via zero-based index

2. Creating Lists

empty = [] # empty list


nums = [1, 2, 3, 4, 5] # list of integers
words = list(("a", "b", "c")) # using list() constructor on a tuple
chars = list("hello") # ['h', 'e', 'l', 'l', 'o']
zeros = [0] * 5 # [0, 0, 0, 0, 0]
nested = [[1, 2], [3, 4]] # list of lists

3. Indexing and Slicing

Lists use zero-based indexing. Negative indices count from the end.

fruits = ["apple", "banana", "cherry", "date", "fig"]

fruits[0] # 'apple' (first element)


fruits[-1] # 'fig' (last element)
fruits[1:3] # ['banana', 'cherry']
fruits[:2] # ['apple', 'banana']
fruits[2:] # ['cherry', 'date', 'fig']
fruits[::-1] # reversed list
fruits[::2] # every second element

4. List Methods (all 11 built-in methods)

append(x)
Adds a single item x to the end of the list.

nums = [1, 2, 3]
[Link](4)
# nums -> [1, 2, 3, 4]

extend(iterable)

Adds all elements of an iterable (list, tuple, string, etc.) to the end of the list.

nums = [1, 2, 3]
[Link]([4, 5])
# nums -> [1, 2, 3, 4, 5]

[Link]("ab")
# nums -> [1, 2, 3, 4, 5, 'a', 'b']

Note: append([4,5]) adds the whole list as one element: [1,2,3,[4,5]] . Use extend() to merge elements individually.

insert(index, x)

Inserts item x at the given position, shifting later elements right.

nums = [1, 2, 4]
[Link](2, 3)
# nums -> [1, 2, 3, 4]

remove(x)

Removes the first occurrence of value x . Raises ValueError if not found.

nums = [1, 2, 3, 2]
[Link](2)
# nums -> [1, 3, 2] (only first 2 removed)

pop(index=-1)

Removes and returns the item at the given index. Default is the last item.

nums = [1, 2, 3]
last = [Link]() # last = 3, nums = [1, 2]
first = [Link](0) # first = 1, nums = [2]

clear()

Removes all items, leaving an empty list.

nums = [1, 2, 3]
[Link]()
# nums -> []

index(x, start=0, end=len)

Returns the index of the first occurrence of x . Raises ValueError if not found.

nums = [10, 20, 30, 20]


[Link](20) # 1
[Link](20, 2) # 3 (search starts from index 2)

count(x)

Returns the number of times x appears in the list.

nums = [1, 2, 2, 3, 2]
[Link](2) # 3

sort(key=None, reverse=False)

Sorts the list in place (modifies original, returns None ).

nums = [5, 2, 8, 1]
[Link]() # [1, 2, 5, 8]
[Link](reverse=True) # [8, 5, 2, 1]

words = ["banana", "kiwi", "fig"]


[Link](key=len) # sort by string length
# ['fig', 'kiwi', 'banana']

reverse()

Reverses the list in place.

nums = [1, 2, 3]
[Link]()
# nums -> [3, 2, 1]

copy()

Returns a shallow copy of the list (equivalent to list[:] ).

original = [1, 2, 3]
duplicate = [Link]()
[Link](4)
# original -> [1, 2, 3] (unaffected)
# duplicate -> [1, 2, 3, 4]

Quick Reference Table

Method Returns Modifies in place? Purpose

append(x) None Yes Add single item to end

extend(iter) None Yes Add all items from iterable

insert(i, x) None Yes Insert item at index

remove(x) None Yes Remove first matching value

pop(i) Removed item Yes Remove & return item at index

clear() None Yes Remove all items

index(x) int No Find index of value

count(x) int No Count occurrences

sort() None Yes Sort list ascending/descending

reverse() None Yes Reverse order in place

copy() New list No Shallow copy

5. Built-in Functions that Work with Lists

Function Example Result

len(list) len([1,2,3]) 3

max(list) max([4,9,2]) 9

min(list) min([4,9,2]) 2

sum(list) sum([1,2,3]) 6

sorted(list) sorted([3,1,2]) [1,2,3] (new list)

list(iterable) list("abc") ['a','b','c']

enumerate(list) list(enumerate(['a','b'])) [(0,'a'),(1,'b')]

zip(list1, list2) list(zip([1,2],['a','b'])) [(1,'a'),(2,'b')]

map(func, list) list(map(str, [1,2])) ['1','2']

filter(func, list) list(filter(lambda x:x>1,[1,2,3])) [2,3]

any(list) any([0, 0, 1]) True

all(list) all([1, 1, 0]) False

Important: sorted() returns a new list and leaves the original unchanged, unlike the .sort() method which sorts in place.

6. Operators on Lists

Operator Example Result Meaning


+ [1,2] + [3,4] [1,2,3,4] Concatenation

* [1,2] * 3 [1,2,1,2,1,2] Repetition

in 2 in [1,2,3] True Membership test

not in 5 not in [1,2,3] True Non-membership

== [1,2] == [1,2] True Equality (element-wise)

del del lst[0] — Delete item/slice by index

7. List Comprehensions

A concise way to build lists in a single readable line.

# Basic: squares of 0-9


squares = [x**2 for x in range(10)]

# With condition: even numbers only


evens = [x for x in range(20) if x % 2 == 0]

# With if-else
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]

# Nested loop (flatten a 2D list)


matrix = [[1, 2], [3, 4]]
flat = [num for row in matrix for num in row]
# flat -> [1, 2, 3, 4]

8. Copying Lists — Shallow vs Deep

# WRONG: this just creates another reference to the same list


a = [1, 2, 3]
b = a
[Link](4) # 'a' is also changed! a -> [1,2,3,4]

# Shallow copy (fine for flat lists)


c = [Link]() # or c = a[:] or c = list(a)

# Deep copy (needed for nested lists)


import copy
nested = [[1, 2], [3, 4]]
deep = [Link](nested)

Tip: A shallow copy duplicates the outer list, but inner lists are still shared references. Use [Link]() when working with nested/2D lists
that must be fully independent.

9. Nested Lists / 2D Lists

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

matrix[1][2] # 6 (row 1, column 2)

# Creating a 2D list correctly (avoid shared-reference bug)


rows, cols = 3, 3
grid = [[0] * cols for _ in range(rows)] # correct way
# grid = [[0]*cols]*rows -> BUG: all rows share same list!

10. Common Patterns and Tips

Task Code

Remove duplicates (order lost) list(set(my_list))

Remove duplicates (order kept) list([Link](my_list))


Find sum of a list sum(my_list)

Check if list is empty if not my_list:

Swap two elements lst[i], lst[j] = lst[j], lst[i]

Flatten nested list [x for row in matrix for x in row]

Get index + value while looping for i, v in enumerate(lst):

Combine two lists element-wise list(zip(lst1, lst2))

Common Exam/Interview Pitfalls:


1. sort() returns None — never write lst = [Link]() .
2. remove() deletes by value, pop() deletes by index.
3. Assigning b = a does NOT copy a list — both names point to the same object.
4. Lists are mutable, so they cannot be used as dictionary keys or set elements (tuples can).

Python List Tutorial — Complete Reference Guide

You might also like