Information Technology Tips

Innotechtips_logo_v4
Menu
  • Home
  • Linux
  • Programming
  • Other Tech Tips
    • Windows
    • Security
Youtube
Home Programming

List and Tuples in Python Programming – An Overview

Inno by Inno
July 27, 2023
List and Tuples in Python Programming – An Overview

List and Tuples in Python – An Overview

A list is a Python built-in data structure that allows you to store a bunch of related objects (in one variable) and process different types of objects (integers, strings, lists, dictionaries, etc.). The list can contain the same kind of objects (e.g., strings only) or a mixture of objects (e.g., integers and strings). Contents inside a list are ordered in that they maintain their position within the list. Lists are also mutable, which means that data inside the list can be changed, lists can grow (you can add objects), and lists can shrink (you can remove objects).

Lists are enclosed in square brackets, and the objects contained within the list have always separated a comma.

Empty list creation:

List1 = []

List2 = list()

List derived from a string:

word1 = ‘This is a string’ word_list = list(word1)

List methods

The built-in function dir can be used to display the attributes and methods associated with lists in Python.

dir(list)  # Use dir (built-in function) to view list attributes and methods

The built-in function, help, can be used to display more details on the different methods and attributes associated with dictionaries.

help(list.append)   # Use help to view details on list attributes and methods

Some commonly used list methods are append, remove, insert, pop, extend, and copy

Append() method

#Adds an item to the end of the list

>>> list1 = [1,2,3]

>>> list1.append(5)

>>> print(list1)

[1, 2, 3, 5]

>>>

Remove() method

# Removes the first occurrence of an item

>> list1.remove(2)

>>> print(list1)

[1, 3, 5]

>>>

Insert() method

#Inserts a specified object in a specified position or location or index

>> list1.insert(1,8)
>>> print(list1)

[1, 8, 3, 5]

>>>

Pop() method

#Removes and returns an object in a specified position. The default position is the last object.

>>> list1 = [ 1, 2, 4]

>>> print(list1.pop())

4

>>>

Extend() method

#Expands a list by adding items of another object to the end of a list

>>> list1 = [ 1, 2, 4]

>>> list1.extend([6, 7])

>>> print(list1)

[1, 2, 4, 6, 7]

>>>

Lists Square Bracket Notation

The square bracket notation allows you to select individual objects or items from within a list. The syntax involves the name of the list, followed by brackets, and the index position of the item inside the bracket. Python counts the index positions from zero onwards, therefore, the first index location is referred to using index zero. Python also understands negative index positions which allows you to list objects in reverse order.

Example:

>>> nums = [ 2, 5, 8, 9, 3]

>>> first_num = nums[0]

>>> last_num = nums[-1]

>>> print(first_num)

2

>>> print(last_num)

3

>>>

Lists Understanding Start, Stop, and Step [ start : stop : step ] Slice Notation

Lists also provide slices (or fragmentation) of a list by specifying the start, stop, and step within the square brackets.

Recall what start, stop, and step mean when it comes to specifying ranges (and let's relate them to lists):

>The START value lets you control WHERE the range begins.

 When used with lists, the start value indicates the starting index value.

> The STOP value lets you control WHEN the range ends.

 When used with lists, the stop value indicates the index value to stop at but is not included.

> The STEP value lets you control HOW the range is generated.

 When used with lists, the step value refers to the stride to take

When used with lists, start, stop, and step are specified within the square brackets and are separated from each other by the colon (:) character. The use of this start, stop, step slice notation with lists is very powerful.

Examples:

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

print(nums[0:7:2])  Start at index zero, stop at index 7, and step by two (or take 2 strides)

[1, 3, 5, 7]

print(nums[4:]) # Start at index four, stop at the end, and step by 1 (or take 1 stride)

[5, 6, 7, 8, 9, 10]

print(nums[:5]) # Start at index zero, stop at index 5, and step by 1 (or take 1 stride)

[1, 2, 3, 4, 5]

print(nums[::3]) # Start at index zero, stop at the end, and step by 3 (or take 3 strides)

[1, 4, 7, 10]

print(nums[::-1]) # Take 1 stride in reverse, hence printing the whole list in reverse order)

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

NOTE: Unlike when using list methods, slicing is non-destructive as it does not change/modify the original list. Slicing allows you to extract objects from an existing list without altering it.

For loop with lists
>>> nums = [ 1, 2, 3]

>>> for num in nums:

            print(num)

1

2

3

>>> 

For loop with slices

>>> nums = [ 1, 2, 3 ]

>>> for num in nums[:2]:

            print(num)

1

2

>>>

TUPLES

A tuple is an ordered immutable collection of objects. A tuple is an immutable list. This means that once you assign objects to a tuple, the tuple cannot be changed. It is often useful to think of a tuple as a constant list. There are plenty of use cases where you may want to ensure that your objects cannot be changed by your (or anyone else’s) code.

Tuples are enclosed in parenthesis:

Letters = ( ‘a’, ‘b’, ‘c’)

Methods

Tuples only have a limited number of methods due to being immutable/unchangeable.

The count method takes one argument which is the item within the tuple that has to be counted.

>>> letters = ('a', 'b', 'c')

>>> print(letters.count('a'))  # returns number of occurrence of value ‘a’

1

>>> 

Index() method

The index method returns the first index of a value.

>>> letters = ('a', 'b', 'c')

>>> print(letters.index('c')) # returns the index of ‘c’

2

>>>
Inno

Inno

Related Posts

http://innotechtips.com
Programming

10 Reasons Why You Should Learn Python

July 17, 2023
Exploring Built-in Functions in Python
Programming

Exploring Built-in Functions in Python

July 27, 2023
Dictionaries and Sets in Python
Programming

Dictionaries and Sets in Python

July 27, 2023
Introduction to Functions in Python
Programming

Introduction to Functions in Python

July 27, 2023

Category

  • Linux
  • Other Tech Tips
  • Programming
  • Windows

Recommended.

Getting Started with Kali Linux: A Guide for Beginners

July 31, 2024
Python Tutorial – IF Conditional Statement, For Loop, and While Loop

Python Tutorial – IF Conditional Statement, For Loop, and While Loop

July 27, 2023

Trending.

How To Connect Kali Linux to Wi-Fi on VirtualBox

October 9, 2023

How to Install and Enable Free VPN in Kali Linux

July 27, 2023

How to Capture Network Traffic on a Wi-Fi Network using Kali Linux

July 27, 2023

How to Connect Kali Linux on VMware Workstation to a Wi-Fi Network

July 27, 2023
How to Connect to Kali Linux from Window’s Command Prompt

How to Connect to Kali Linux from Window’s Command Prompt

July 27, 2023

About us

This site is dedicated towards highlighting various important aspects of information technology. The key areas includes programming, Linux, software, and security. The content will include articles as well as videos.

Quick Links

Menu
  • Home
  • Linux
  • Programming
  • Other Tech Tips
    • Windows
    • Security

Privacy Policy

Menu
  • Privacy Policy
Manage Cookie Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
View preferences
{title} {title} {title}
No Result
View All Result
  • Cookie Policy (EU)
  • Home 1
  • Home 2
  • Home 3
  • Mytest Page
  • Privacy Policy

© 2025 JNews - Premium WordPress news & magazine theme by Jegtheme.