StudyLover
  • Home
  • Study Zone
  • Profiles
  • Contact us
  • Sign in
StudyLover Basic List Operators
Download
  1. Python
  2. Problem Solving: Lists, Dictionaries, and Function-Based Design
Functions : Replacing Elements
Problem Solving: Lists, Dictionaries, and Function-Based Design

Basic List Operators

Python provides several operators that can be used with lists to perform various operations:

Indexing and Slicing

  • Indexing: Accessing individual elements using their index.

Python

my_list = [1, 2, 3]

first_element = my_list[0]  # Output: 1

  • Slicing: Extracting a sublist using a range of indices.

Python

sublist = my_list[1:3]  # Output: [2, 3]

Concatenation

  • +: Concatenates two lists.

Python

list1 = [1, 2]

list2 = [3, 4]

combined_list = list1 + list2  # Output: [1, 2, 3, 4]

Membership Testing

  • in: Checks if an element is present in the list.

Python

if 2 in my_list:

    print("2 is in the list")

  • not in: Checks if an element is not present in the list.

Repetition

  • *: Repeats a list multiple times.

Python

repeated_list = my_list * 3  # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

Comparison

  • ==: Compares two lists for equality (element-wise).

  • !=: Compares two lists for inequality.

  • <, <=, >, >=: Compares lists lexicographically (based on the order of elements).

Example

Python

list1 = [1, 2, 3]

list2 = [3, 4, 5]

 

# Indexing

print(list1[0])  # Output: 1

 

# Slicing

print(list1[1:2])  # Output: [2]

 

# Concatenation

combined_list = list1 + list2

print(combined_list)  # Output: [1, 2, 3, 3, 4, 5]

 

# Membership testing

if 2 in list1:

    print("2 is in list1")

 

# Repetition

repeated_list = list1 * 2

print(repeated_list)  # Output: [1, 2, 3, 1, 2, 3]

 

# Comparison

if list1 < list2:

    print("list1 is less than list2")

These operators provide a powerful foundation for working with lists in Python.

Functions Replacing Elements
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website