• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Python Lists| Lists Traversal| Lists Concatenation| Lists Membership| Lists Repetition

  • October 1, 2022
  • CODE OF GEEKS
  • 0
Python Lists : In this Unit…
  • Python Lists Basics
  • index() method in list
  • append() method in list
  • insert() method in list
  • copy() method in list
  • remove() method in list
  • pop() method in list
  • sort() method in list
  • reverse() method in list
  • clear() method in list
  • Nested Lists in Python
  • List Comprehensions in Python


Python List is a collection of different elements that are grouped under an object. This object denotes a list in Python. In Python, Lists are denoted with a special keyword called list and are enclosed within [ ] (big brackets).

[1, 2, 3],
[1, “hey”, [1,2]],
[],
[[]], are all valid Python Lists.

Additionally, We can also use list() to typecast any iterable object to a list. Like below,

s = "cog" # string
n = {10} # set
t = (4, 5,) # tuple
print(list(s)) # string -> list
print(list(n)) # set -> list
print(list(t)) # tuple -> list

O/P

[‘c’, ‘o’, ‘g’]
[10]
[4, 5]

Generally, Python List also works in a similar fashion as traditional arrays, but the major difference between Python List and an Array is that : Python List can contain elements of different datatypes whereas an array can only contain similar type of elements.

Length of a Python List

Length of a Python List signifies the number of elements in that particular list. We can use the len() function to find the length of a list.

l = [3, "hello", "nice", 4]
print(len(l)) # prints 4

Indexing in Python Lists

Indexing in Python Lists

Indexing in Python lists is same as in Python Strings, starting with 0 to len(lst)-1.

Python Lists also supports negative indexing, starting from -1 to len(lst). So,

lst[0] will give us 10,
lst[1] will give us “hello”,
Similarly, lst[-2] will give us 30.

Python Lists are mutable

A mutable object is an object whose content (data stored in that object) can be changed. If we talk about Python specifically, we have list, set, dictionary, user defined classes as mutable objects.

Python Lists are mutable, this means that we can modify the data inside a Python list. Let’s see how,

lst = [10, “hello”, 30, 50]
print("List before modification", lst)
lst[1] = 3 # modifying second element from left 
lst[-2] = 60 # modifiying second element from right 
print("List after modification", lst)

O/P

List before modification [10, ‘hello’, 30, 50]
List after modification [10, 3, 60, 50]

From the output, it is evident that we were able to modify the content of the given list with our own values, this defines the mutability concept of Python list.



Traversing a Python List

Traversal, in simpler words, means to visit each element of the given list one by one.

Traversing a Python List

In Python Lists, traversal can be done in two ways :

1. for loop
2. while loop

Traversing list using for loop

Program : To traverse a given list of items using for loop.

planets = ['mercury', 'venus', 'earth', 'mars']
for each_planet in planets:
    print(each_planet, end=' ')

O/P :

mercury venus earth mars

Here, variable ‘each_planet’ is acting as a list element (iterator).

We can also iterate over a given sequence using range() function within the for loop.

Extra Gyan !

range() function in Python is used to generate a sequence or series of numbers, starting from 0, ending just before the given limit and increments by 1. These are the default values which can be changed as per the requirements.

Syntax

range(start, end+1, step_size)

start : This signifies the starting point of the sequence.

end : This signifies the ending point of the sequence.

step_size : This signifies the value with which each digit of sequence will either increase or decrease.

Like, in series 2, 4, 6, 8, we have two as a step size.

Below are the different ways in which range() function can be used :

1. range(n) : We will use this when we want to generate a sequence of numbers from 0 to n-1, keeping 1 as step size.

2. range(0, 10) : We will use this when we want to generate a sequence of numbers from 0 to 9, keeping 1 as step size.

3. range(0, 10, 2) : We will use this when we want to generate a sequence of numbers from 0 to 9, keeping 2 as step size. This series will be as ‘0, 2, 4, 6, 8’.

4. range(10, 0, -1) : We will use this when we want to generate a sequence of numbers from 10 to 1,

Program : To traverse a given list of items using for loop (range).

planets = ['mercury', 'venus', 'earth', 'mars']
for i in range(0, len(planets)):
    print(planets[i], end=' ')

# reverse order 
for i in range(len(planets)-1, -1, -1):
    print(planets[i], end=' ')

# reverse using negative indexing 
for i in range(-1, -(len(planets))-1, -1): # loop will run for index -1 to -4
    print(planets[i], end=' ')

O/P :

mercury venus earth mars
mars earth venus mercury
mars earth venus mercury

We all know that just like arrays, Python Lists are indexable too. In the above program, we were able to access each element of the given list with its index using range() function.

Consider line-3 of code

for i in range(0, len(planets)):

This for loop will run ‘len(planets)’ times, starting from i = 0 and ending at i = len(planets) – 1.

Variable ‘i‘ holds integer value.

Here, in our program, len(planets) = 4

Hence, this for loop will run four times, starting from 0 and ending to 3.



Traversing list using while loop

Program : To traverse a given list of items using while loop.

planets = ['mercury', 'venus', 'earth', 'mars']
i = 0 
while i < len(planets):
  print(planets[i], end= ' ')
  i+=1

# reverse order 
j = len(planets)-1
while j >= 0:
  print(planets[j], end= ' ')
  j-=1

O/P :

mercury venus earth mars
mars earth venus mercury

Taking lists as an Input

We can use input() method to take input from the user, which can be later type-casted to list.

s = list(input('Enter your list : ')) 
print("List is : ",s)

O/P

Enter your list : 23456

List is : [2, 3, 4, 5, 6]

You can read more about different ways of taking list input here : http://codeofgeeks.com/taking-inputs-in-python/

Concatenation of Python Lists

Concatenation refers to the process of attaching two or more lists to form a resultant list.

We can simple use ‘+’ operator to perform list concatenation.

inner_planets = ['mercury', 'venus', 'earth', 'mars'] # list1
outer_planets = ['jupiter', 'saturn', 'uranus', 'neptune'] # list2
star = ["sun"] # list3
planets = inner_planets + outer_planets # concatenating two lists
print("All Planets : ", planets)
solar_system = star + planets # concatenating two lists again
print("Our Solar System : ", solar_system)

O/P

All Planets : [‘mercury’, ‘venus’, ‘earth’, ‘mars’, ‘jupiter’, ‘saturn’, ‘uranus’, ‘neptune’]
Our Solar System : [‘sun’, ‘mercury’, ‘venus’, ‘earth’, ‘mars’, ‘jupiter’, ‘saturn’, ‘uranus’, ‘neptune’]



Repetition of Lists

Repetition refers to the process of repeating the elements of a list ‘n’ number of times.

We can simple use ‘*’ operator to perform list repetition.

If we write, l*n, then it means list l will be repeated n number of times.

l = [2, 4, 6]
print(l * 3)

O/P

[2, 4, 6, 2, 4, 6, 2, 4, 6]

Here, list l, is repeated thrice as specified.

Membership in Python Lists

Suppose if we want to check whether a given element (or a sublist) is a member of the given list.

This can be done using in and not in operator in Python.

If the element is the member of the list, then, in operator returns True, else False.

If the element is not the member of the list, then, not in operator returns True, else False.

l = [1, 2, 3, 4, 5] 
item = 10 
print(item in l) # checking for 10 in given list, returns False
print(item not in l) # returns True

O/P

False
True

Extra Gyan !

Both in and not in operator usually perform a traversal to look out for the given element in the list. In case of lists, it takes O(N) time complexity to perform traversal.

But, in case of Sets, Dictionary, operators do it in an optimized way with O(1) time complexity.

That’s all here, you can learn more about list methods in our next lessons.





  • Previous Finding index of element in Python Lists| index() method in Python Lists
  • Next string.endswith() method in Python Strings

Leave a Reply Cancel reply

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

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.