Day 5: Python Syntax: Basic Concepts — List in detail

Day 5: Python Syntax: Basic Concepts — List in detail

Python in 30 Days: A Practical and Theoretical Approach for Beginner.

list is one of the most commonly used data structures in Python.

image 41 Simply Creative Minds
  • It is a collection of ordered, mutable (changeable), and heterogeneous elements.
  • Lists allow you to store multiple items in a single variable.
  • Lists are defined by square brackets [].

Characteristics of Lists:

  1. Ordered: The items in a list have a specific order, and this order is maintained.
  2. Mutable: You can change the elements in a list (add, remove, modify).
  3. Heterogeneous: A list can store elements of different data types (e.g., integers, strings, or even other lists).

SYNTAX

list_name = [element1, element2, element3, ...]

Example of List in Python

Creating a List

# Creating a List
fruits = ["apple", "banana", "cherry", "orange"]

Accessing elements by index (starting from 0)

print(fruits[0])  # Output: apple
print(fruits[2])  # Output: cherry

Negative indexing (accessing from the end of the list)

print(fruits[-1])  # Output: orange
print(fruits[-2])  # Output: cherry

Slicing a list

print(fruits[1:3])  
#Output: ['banana', 'cherry'] (items at index 1 and 2)

Modifying an element in the list

fruits[1] = "blueberry"
print(fruits)  
#Output: ['apple', 'blueberry', 'cherry', 'orange']

Adding an element to the list using append()

fruits.append("grape")
print(fruits)  
#Output : ['apple', 'blueberry', 'cherry', 'orange', 'grape']

 Inserting an element at a specific position

fruits.insert(2, "kiwi")
print(fruits)  
# Output: ['apple', 'blueberry', 'kiwi', 'cherry', 'orange', 'grape'];

Removing an element from the list

fruits.remove("cherry")
print(fruits)  
# Output: ['apple', 'blueberry', 'kiwi', 'orange', 'grape']

Popping an element (removes the last item by default)

# Popping an element (removes the last item by default)
popped_item = fruits.pop()
print(popped_item)  # Output: grape
print(fruits)  
# Output: ['apple', 'blueberry', 'kiwi', 'orange']

Length of the list

# Length of the list
print(len(fruits))  
# Output: 4

Check if an item exists in the list

# Check if an item exists in the list
print("kiwi" in fruits)  
# Output: True
print("mango" in fruits)  
# Output: False

Lists in Python are versatile and easy to use.

They are the go-to structure for many tasks, such as storing and manipulating collections of data.

We can easily access, modify, and perform operations like appending, inserting, and removing elements with just a few lines of code.

Happy Coding and Stay Tuned 🙂

Kind is always cool !!!

Share knowledge to gain knowledge !!!!

Be kind and treat people with respect !!!

If you find my blog helpful, then please subscribe, claps and follow to support 🙂

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *