Answers for "working with lists in python"

1

working with lists in python

FOLLOW THROUGH THIS BY TYPING THE CODE IN YOUR SCRIPT/INTERPRETER

# Printing a simple list
print("WORKING WITH LISTS AND MANIPULATING THEM \n")
numbers = ["one", "two", "three"]
print("Original list:\t {} \n".format(numbers))

# Changing an element in a list
numbers[2] = "change three"
print("After changing numbers[3] the list became:\t {} \n".format(numbers))

# Adding elements to the end of a list
numbers.append("append four")
print("After appending 'four':\t {} \n".format(numbers))

# Inserting elements at specific positions in a list
numbers.insert(4, "insert five")
print("After inserting five:\t {} ".format(numbers))

numbers.insert(0, "insert zero")
print("insert zero at the beginning:\t {} \n".format(numbers))

# Removing an item in a list 
del numbers[0]
print("Remove 'insert zero':\t {} \n".format(numbers))

# Using pop to remove the last element of a list and printing it
popped_item = numbers.pop()
print("The popped item is:\t {} \n".format(popped_item))
print("Popped the last item:\t {}".format(numbers))

# Using pop(index) to remove an item from any position in the list
"""Passing a number in pop will remove the item in that index"""
pop_one = numbers.pop(0)
print("We have popped:\t {}".format(pop_one))
print("After popping one:\t {}\n".format(numbers))

# Using remove() to remove a list item by value
numbers.remove("two")
print("After removing two:\t {}".format(numbers))

--------
THE OUTPUT
WORKING WITH LISTS AND MANIPULATING THEM

Original list:   ['one', 'two', 'three']

After changing numbers[3] the list became:       ['one', 'two', 'change three']

After appending 'four':  ['one', 'two', 'change three', 'append four']

After inserting five:    ['one', 'two', 'change three', 'append four', 'insert five']
insert zero at the beginning:    ['insert zero', 'one', 'two', 'change three', 'append four', 'insert five']

Remove 'insert zero':    ['one', 'two', 'change three', 'append four', 'insert five']

The popped item is:      insert five

Popped the last item:    ['one', 'two', 'change three', 'append four']
We have popped:  one
After popping one:       ['two', 'change three', 'append four']

After removing two:      ['change three', 'append four']
Posted by: Guest on October-17-2021
17

add item to list python

list.append(item)
Posted by: Guest on June-24-2020
6

how to create a list in python

#creating a list
create_list = ["apple", "banana", "cherry"]
print(create_list)
Posted by: Guest on September-30-2020
2

python dlist

#this is how  to create a list:
#I named it mylist, but you can name it whatever you like

myList = [1,2,3,4,5]
print(myList[0]) # this will print the first element of the list
print(myList[1]) #this will print the second element of the list
print(myList[2])#and so on
print(myList[3])
print(myList[4])
Posted by: Guest on April-08-2020

Python Answers by Framework

Browse Popular Code Answers by Language